vboot2: Add common functions

This is the third of several CLs adding a more memory- and
code-efficient firmware verification library.

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

Change-Id: I3a5daa5438afc5598d3dfcf5a597ffb16eda8749
Signed-off-by: Randall Spangler <rspangler@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/200140
Reviewed-by: Bill Richardson <wfrichar@chromium.org>
diff --git a/Makefile b/Makefile
index e2bd891..2b5c1e2 100644
--- a/Makefile
+++ b/Makefile
@@ -568,6 +568,8 @@
 ifneq (${VBOOT2},)
 TEST_NAMES += \
 	tests/vb2_common_tests \
+	tests/vb2_common2_tests \
+	tests/vb2_common3_tests \
 	tests/vb2_misc_tests \
 	tests/vb2_nvstorage_tests \
 	tests/vb2_rsa_padding_tests \
@@ -945,6 +947,8 @@
 ${BUILD}/utility/vbutil_keyblock: LDLIBS += ${CRYPTO_LIBS}
 
 ${BUILD}/host/linktest/main: LDLIBS += ${CRYPTO_LIBS}
+${BUILD}/tests/vb2_common2_tests: LDLIBS += ${CRYPTO_LIBS}
+${BUILD}/tests/vb2_common3_tests: LDLIBS += ${CRYPTO_LIBS}
 ${BUILD}/tests/vboot_common2_tests: LDLIBS += ${CRYPTO_LIBS}
 ${BUILD}/tests/vboot_common3_tests: LDLIBS += ${CRYPTO_LIBS}
 
@@ -1095,6 +1099,8 @@
 .PHONY: run2tests
 run2tests: test_setup
 	${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}
 	${RUNTEST} ${BUILD_RUN}/tests/vb2_misc_tests
 	${RUNTEST} ${BUILD_RUN}/tests/vb2_nvstorage_tests
 	${RUNTEST} ${BUILD_RUN}/tests/vb2_rsa_utility_tests
@@ -1114,6 +1120,10 @@
 runlongtests: test_setup genkeys genfuzztestcases
 	${RUNTEST} ${BUILD_RUN}/tests/vboot_common2_tests ${TEST_KEYS} --all
 	${RUNTEST} ${BUILD_RUN}/tests/vboot_common3_tests ${TEST_KEYS} --all
+ifneq (${VBOOT2},)
+	${RUNTEST} ${BUILD_RUN}/tests/vb2_common2_tests ${TEST_KEYS} --all
+	${RUNTEST} ${BUILD_RUN}/tests/vb2_common3_tests ${TEST_KEYS} --all
+endif
 	tests/run_preamble_tests.sh --all
 	tests/run_vbutil_tests.sh --all
 
diff --git a/firmware/2lib/2common.c b/firmware/2lib/2common.c
index 9849b22..9099f6f 100644
--- a/firmware/2lib/2common.c
+++ b/firmware/2lib/2common.c
@@ -8,6 +8,8 @@
 
 #include "2sysincludes.h"
 #include "2common.h"
+#include "2rsa.h"
+#include "2sha.h"
 
 int vb2_align(uint8_t **ptr, uint32_t *size, uint32_t align, uint32_t want_size)
 {
@@ -89,7 +91,316 @@
 	wb->size += size;
 }
 
+const uint8_t *vb2_packed_key_data(const struct vb2_packed_key *key)
+{
+	return (const uint8_t *)key + key->key_offset;
+}
+
+uint8_t *vb2_signature_data(struct vb2_signature *sig)
+{
+	return (uint8_t *)sig + sig->sig_offset;
+}
+
 ptrdiff_t vb2_offset_of(const void *base, const void *ptr)
 {
 	return (uintptr_t)ptr - (uintptr_t)base;
 }
+
+int vb2_verify_member_inside(const void *parent, uint32_t parent_size,
+			     const void *member, uint32_t member_size,
+			     uint32_t member_data_offset,
+			     uint32_t member_data_size)
+{
+	const size_t psize = (size_t)parent_size;
+	const uintptr_t parent_end = (uintptr_t)parent + parent_size;
+	const ptrdiff_t member_offs = vb2_offset_of(parent, member);
+	const ptrdiff_t member_end_offs = member_offs + member_size;
+	const ptrdiff_t data_offs = member_offs + member_data_offset;
+	const ptrdiff_t data_end_offs = data_offs + member_data_size;
+
+	/* Make sure parent doesn't wrap */
+	if (parent_end < (uintptr_t)parent)
+		return VB2_ERROR_UNKNOWN;
+
+	/*
+	 * Make sure the member is fully contained in the parent and doesn't
+	 * wrap.  Use >, not >=, since member_size = 0 is possible.
+	 */
+	if (member_end_offs < member_offs)
+		return VB2_ERROR_UNKNOWN;
+	if (member_offs > psize || member_end_offs > psize)
+		return VB2_ERROR_UNKNOWN;
+
+
+	/* Make sure parent fully contains member data */
+	if (data_end_offs < data_offs)
+		return VB2_ERROR_UNKNOWN;
+	if (data_offs > psize || data_end_offs > psize)
+		return VB2_ERROR_UNKNOWN;
+
+	return VB2_SUCCESS;
+}
+
+int vb2_verify_signature_inside(const void *parent,
+				uint32_t parent_size,
+				const struct vb2_signature *sig)
+{
+	return vb2_verify_member_inside(parent, parent_size,
+					sig, sizeof(*sig),
+					sig->sig_offset, sig->sig_size);
+}
+
+int vb2_verify_packed_key_inside(const void *parent,
+				 uint32_t parent_size,
+				 const struct vb2_packed_key *key)
+{
+	return vb2_verify_member_inside(parent, parent_size,
+					key, sizeof(*key),
+					key->key_offset, key->key_size);
+}
+
+int vb2_unpack_key(struct vb2_public_key *key,
+		   const uint8_t *buf,
+		   uint32_t size)
+{
+	const struct vb2_packed_key *packed_key =
+		(const struct vb2_packed_key *)buf;
+	const uint32_t *buf32;
+	uint32_t expected_key_size;
+	int rv;
+
+	/* Make sure passed buffer is big enough for the packed key */
+	rv = vb2_verify_packed_key_inside(buf, size, packed_key);
+	if (rv)
+		return rv;
+
+	if (packed_key->algorithm >= VB2_ALG_COUNT) {
+		VB2_DEBUG("Invalid algorithm.\n");
+		return VB2_ERROR_BAD_ALGORITHM;
+	}
+
+	expected_key_size = vb2_packed_key_size(packed_key->algorithm);
+	if (!expected_key_size || expected_key_size != packed_key->key_size) {
+		VB2_DEBUG("Wrong key size for algorithm\n");
+		return VB2_ERROR_BAD_KEY;
+	}
+
+	/* Make sure source buffer is 32-bit aligned */
+	buf32 = (const uint32_t *)vb2_packed_key_data(packed_key);
+	if (!vb_aligned(buf32, sizeof(uint32_t)))
+		return VB2_ERROR_BUFFER_UNALIGNED;
+
+	/* Sanity check key array size */
+	key->arrsize = buf32[0];
+	if (key->arrsize * sizeof(uint32_t) !=
+	    vb2_rsa_sig_size(packed_key->algorithm))
+		return VB2_ERROR_BAD_KEY;
+
+	key->n0inv = buf32[1];
+
+	/* Arrays point inside the key data */
+	key->n = buf32 + 2;
+	key->rr = buf32 + 2 + key->arrsize;
+
+	key->algorithm = packed_key->algorithm;
+
+	return VB2_SUCCESS;
+}
+
+int vb2_verify_data(const uint8_t *data,
+		    uint32_t size,
+		    struct vb2_signature *sig,
+		    const struct vb2_public_key *key,
+		    struct vb2_workbuf *wb)
+{
+	struct vb2_workbuf wblocal = *wb;
+	struct vb2_digest_context *dc;
+	uint8_t *digest;
+	uint32_t digest_size;
+	int rv;
+
+	if (key->algorithm >= VB2_ALG_COUNT)
+		return VB2_ERROR_BAD_ALGORITHM;
+
+	if (sig->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)sig->sig_size, vb2_rsa_sig_size(key->algorithm),
+			 key->algorithm);
+		return VB2_ERROR_BAD_SIGNATURE;
+	}
+
+	if (sig->data_size > size) {
+		VB2_DEBUG("Data buffer smaller than length of signed data.\n");
+		return VB2_ERROR_UNKNOWN;
+	}
+
+	/* Digest goes at start of work buffer */
+	digest_size = vb2_digest_size(key->algorithm);
+	digest = vb2_workbuf_alloc(&wblocal, digest_size);
+	if (!digest)
+		return VB2_ERROR_WORKBUF_TOO_SMALL;
+
+	/* Hashing requires temp space for the context */
+	dc = vb2_workbuf_alloc(&wblocal, sizeof(*dc));
+	if (!dc)
+		return VB2_ERROR_WORKBUF_TOO_SMALL;
+
+	rv = vb2_digest_init(dc, key->algorithm);
+	if (rv)
+		return rv;
+
+	rv = vb2_digest_extend(dc, data, sig->data_size);
+	if (rv)
+		return rv;
+
+	rv = vb2_digest_finalize(dc, digest, digest_size);
+	if (rv)
+		return rv;
+
+	vb2_workbuf_free(&wblocal, sizeof(*dc));
+
+	return vb2_verify_digest(key, vb2_signature_data(sig), digest,
+				 &wblocal);
+}
+
+int vb2_verify_keyblock(struct vb2_keyblock *block,
+			uint32_t size,
+			const struct vb2_public_key *key,
+			struct vb2_workbuf *wb)
+{
+	struct vb2_signature *sig;
+	int rv;
+
+	/* Sanity checks before attempting signature of data */
+	if(size < sizeof(*block)) {
+		VB2_DEBUG("Not enough space for key block header.\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+	if (memcmp(block->magic, KEY_BLOCK_MAGIC, KEY_BLOCK_MAGIC_SIZE)) {
+		VB2_DEBUG("Not a valid verified boot key block.\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+	if (block->header_version_major != KEY_BLOCK_HEADER_VERSION_MAJOR) {
+		VB2_DEBUG("Incompatible key block header version.\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+	if (size < block->keyblock_size) {
+		VB2_DEBUG("Not enough data for key block.\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+
+	/* Check signature */
+	sig = &block->keyblock_signature;
+
+	if (vb2_verify_signature_inside(block, block->keyblock_size, sig)) {
+		VB2_DEBUG("Key block signature off end of block\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+
+	/* Make sure advertised signature data sizes are sane. */
+	if (block->keyblock_size < sig->data_size) {
+		VB2_DEBUG("Signature calculated past end of block\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+
+	VB2_DEBUG("Checking key block signature...\n");
+	rv = vb2_verify_data((const uint8_t *)block, size, sig, key, wb);
+	if (rv) {
+		VB2_DEBUG("Invalid key block signature.\n");
+		return VB2_ERROR_BAD_SIGNATURE;
+	}
+
+	/* Verify we signed enough data */
+	if (sig->data_size < sizeof(struct vb2_keyblock)) {
+		VB2_DEBUG("Didn't sign enough data\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+
+	/* Verify data key is inside the block and inside signed data */
+	if (vb2_verify_packed_key_inside(block, block->keyblock_size,
+					 &block->data_key)) {
+		VB2_DEBUG("Data key off end of key block\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+	if (vb2_verify_packed_key_inside(block, sig->data_size,
+					 &block->data_key)) {
+		VB2_DEBUG("Data key off end of signed data\n");
+		return VB2_ERROR_BAD_KEYBLOCK;
+	}
+
+	/* Success */
+	return VB2_SUCCESS;
+}
+
+int vb2_verify_fw_preamble(struct vb2_fw_preamble *preamble,
+			   uint32_t size,
+			   const struct vb2_public_key *key,
+			   struct vb2_workbuf *wb)
+{
+	struct vb2_signature *sig = &preamble->preamble_signature;
+
+	VB2_DEBUG("Verifying preamble.\n");
+
+	/* Sanity checks before attempting signature of data */
+	if(size < EXPECTED_VB2FIRMWAREPREAMBLEHEADER2_1_SIZE) {
+		VB2_DEBUG("Not enough data for preamble header 2.1.\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+	if (preamble->header_version_major !=
+	    FIRMWARE_PREAMBLE_HEADER_VERSION_MAJOR) {
+		VB2_DEBUG("Incompatible firmware preamble header version.\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	if (preamble->header_version_minor < 1) {
+		VB2_DEBUG("Only preamble header 2.1+ supported\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	if (size < preamble->preamble_size) {
+		VB2_DEBUG("Not enough data for preamble.\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	/* Check signature */
+	if (vb2_verify_signature_inside(preamble, preamble->preamble_size,
+					sig)) {
+		VB2_DEBUG("Preamble signature off end of preamble\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	/* Make sure advertised signature data sizes are sane. */
+	if (preamble->preamble_size < sig->data_size) {
+		VB2_DEBUG("Signature calculated past end of the block\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	if (vb2_verify_data((const uint8_t *)preamble, size, sig, key, wb)) {
+		VB2_DEBUG("Preamble signature validation failed\n");
+		return VB2_ERROR_BAD_SIGNATURE;
+	}
+
+	/* Verify we signed enough data */
+	if (sig->data_size < sizeof(struct vb2_fw_preamble)) {
+		VB2_DEBUG("Didn't sign enough data\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	/* Verify body signature is inside the signed data */
+	if (vb2_verify_signature_inside(preamble, sig->data_size,
+					&preamble->body_signature)) {
+		VB2_DEBUG("Firmware body signature off end of preamble\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	/* Verify kernel subkey is inside the signed data */
+	if (vb2_verify_packed_key_inside(preamble, sig->data_size,
+					 &preamble->kernel_subkey)) {
+		VB2_DEBUG("Kernel subkey off end of preamble\n");
+		return VB2_ERROR_BAD_PREAMBLE;
+	}
+
+	/* Success */
+	return VB2_SUCCESS;
+}
diff --git a/firmware/2lib/include/2common.h b/firmware/2lib/include/2common.h
index 3e70e80..3bb403b 100644
--- a/firmware/2lib/include/2common.h
+++ b/firmware/2lib/include/2common.h
@@ -9,6 +9,7 @@
 #define VBOOT_REFERENCE_VBOOT_2COMMON_H_
 
 #include "2return_codes.h"
+#include "2sha.h"
 #include "2struct.h"
 
 struct vb2_public_key;
@@ -118,4 +119,142 @@
  */
 ptrdiff_t vb2_offset_of(const void *base, const void *ptr);
 
+/*
+ * Helper functions to get data pointed to by a public key or signature.
+ */
+
+const uint8_t *vb2_packed_key_data(const struct vb2_packed_key *key);
+uint8_t *vb2_signature_data(struct vb2_signature *sig);
+
+/**
+ * Verify the data pointed to by a subfield is inside the parent data.
+ *
+ * The subfield has a header pointed to by member, and a separate data
+ * field at an offset relative to the header.  That is:
+ *
+ *   struct parent {
+ *     (possibly other parent fields)
+ *     struct member {
+ *        (member header fields)
+ *     };
+ *     (possibly other parent fields)
+ *   };
+ *   (possibly some other parent data)
+ *   (member data)
+ *   (possibly some other parent data)
+ *
+ * @param parent		Parent data
+ * @param parent_size		Parent size in bytes
+ * @param member		Subfield header
+ * @param member_size		Size of subfield header in bytes
+ * @param member_data_offset	Offset of member data from start of member
+ * @param member_data_size	Size of member data in bytes
+ * @return VB2_SUCCESS, or non-zero if error.
+ */
+int vb2_verify_member_inside(const void *parent, uint32_t parent_size,
+			     const void *member, uint32_t member_size,
+			     uint32_t member_data_offset,
+			     uint32_t member_data_size);
+
+/**
+ * Verify a signature is fully contained in its parent data
+ *
+ * @param parent	Parent data
+ * @param parent_size	Parent size in bytes
+ * @param sig		Signature pointer
+ * @return VB2_SUCCESS, or non-zero if error.
+ */
+int vb2_verify_signature_inside(const void *parent,
+				uint32_t parent_size,
+				const struct vb2_signature *sig);
+
+/**
+ * Verify a packed key is fully contained in its parent data
+ *
+ * @param parent	Parent data
+ * @param parent_size	Parent size in bytes
+ * @param key		Packed key pointer
+ * @return VB2_SUCCESS, or non-zero if error.
+ */
+int vb2_verify_packed_key_inside(const void *parent,
+				 uint32_t parent_size,
+				 const struct vb2_packed_key *key);
+
+/**
+ * Unpack a RSA key for use in verification
+ *
+ * The elements of the unpacked key will point into the source buffer, so don't
+ * free the source buffer until you're done with the key.
+ *
+ * @param key		Destintion for unpacked key
+ * @param buf		Source buffer containing packed key
+ * @param size		Size of buffer in bytes
+ * @return VB2_SUCCESS, or non-zero error code if error.
+ */
+int vb2_unpack_key(struct vb2_public_key *key,
+		   const uint8_t *buf,
+		   uint32_t size);
+
+/* Size of work buffer sufficient for vb2_verify_data() worst case */
+#define VB2_VERIFY_DATA_WORKBUF_BYTES					\
+	(VB2_SHA512_DIGEST_SIZE +					\
+	 VB2_MAX(VB2_VERIFY_DIGEST_WORKBUF_BYTES,			\
+		 sizeof(struct vb2_digest_context)))
+
+/**
+ * Verify data matches signature.
+ *
+ * @param data		Data to verify
+ * @param size		Size of data buffer.  Note that amount of data to
+ *			actually validate is contained in sig->data_size.
+ * @param sig		Signature of data (destroyed in process)
+ * @param key		Key to use to validate signature
+ * @param wb		Work buffer
+ * @return VB2_SUCCESS, or non-zero error code if error.
+ */
+int vb2_verify_data(const uint8_t *data,
+		    uint32_t size,
+		    struct vb2_signature *sig,
+		    const struct vb2_public_key *key,
+		    struct vb2_workbuf *wb);
+
+/* Size of work buffer sufficient for vb2_verify_keyblock() worst case */
+#define VB2_KEY_BLOCK_VERIFY_WORKBUF_BYTES VB2_VERIFY_DATA_WORKBUF_BYTES
+
+/**
+ * Check the sanity of a key block using a public key.
+ *
+ * Header fields are also checked for sanity.  Does not verify key index or key
+ * block flags.  Signature inside block is destroyed during check.
+ *
+ * @param block		Key block to verify
+ * @param size		Size of key block buffer
+ * @param key		Key to use to verify block
+ * @param wb		Work buffer
+ * @return VB2_SUCCESS, or non-zero error code if error.
+ */
+int vb2_verify_keyblock(struct vb2_keyblock *block,
+			uint32_t size,
+			const struct vb2_public_key *key,
+			struct vb2_workbuf *wb);
+
+/* Size of work buffer sufficient for vb2_verify_fw_preamble() worst case */
+#define VB2_VERIFY_FIRMWARE_PREAMBLE_WORKBUF_BYTES VB2_VERIFY_DATA_WORKBUF_BYTES
+
+/**
+ * Check the sanity of a firmware preamble using a public key.
+ *
+ * The signature in the preamble is destroyed during the check.
+ *
+ * @param preamble     	Preamble to verify
+ * @param size		Size of preamble buffer
+ * @param key		Key to use to verify preamble
+ * @param wb		Work buffer
+ * @return VB2_SUCCESS, or non-zero error code if error.
+ */
+int vb2_verify_fw_preamble(struct vb2_fw_preamble *preamble,
+			   uint32_t size,
+			   const struct vb2_public_key *key,
+			   struct vb2_workbuf *wb);
+
 #endif  /* VBOOT_REFERENCE_VBOOT_2COMMON_H_ */
diff --git a/tests/run_vboot_common_tests.sh b/tests/run_vboot_common_tests.sh
deleted file mode 100755
index 658f8dd..0000000
--- a/tests/run_vboot_common_tests.sh
+++ /dev/null
@@ -1,139 +0,0 @@
-#!/bin/bash
-
-# Copyright (c) 2013 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.
-
-# Run verified boot firmware and kernel verification tests.
-
-# Load common constants and variables.
-. "$(dirname "$0")/common.sh"
-
-return_code=0
-
-function test_vboot_common {
-  ${TEST_DIR}/vboot_common_tests
-  if [ $? -ne 0 ]
-  then
-    return_code=255
-  fi
-}
-
-# Test a single key+hash algorithm
-function test_vboot_common2_single {
-    local algonum=$1
-    local keylen=$2
-    local hashalgo=$3
-    echo -e "For signing key ${COL_YELLOW}RSA-$keylen/$hashalgo${COL_STOP}:"
-    echo ${TEST_DIR}/vboot_common2_tests $algonum \
-        ${TESTKEY_DIR}/key_rsa${keylen}.pem \
-        ${TESTKEY_DIR}/key_rsa${keylen}.keyb
-    ${TEST_DIR}/vboot_common2_tests $algonum \
-        ${TESTKEY_DIR}/key_rsa${keylen}.pem \
-        ${TESTKEY_DIR}/key_rsa${keylen}.keyb
-    if [ $? -ne 0 ]
-    then
-        return_code=255
-    fi
-}
-
-# Test all key+hash algorithms
-function test_vboot_common2_all {
-  algorithmcounter=0
-  for keylen in ${key_lengths[@]}
-  do
-    for hashalgo in ${hash_algos[@]}
-    do
-      test_vboot_common2_single $algorithmcounter $keylen $hashalgo
-      let algorithmcounter=algorithmcounter+1
-    done
-  done
-}
-
-# Test only the algorithms we actually use
-function test_vboot_common2 {
-    test_vboot_common2_single 4 2048 sha256
-    test_vboot_common2_single 7 4096 sha256
-    test_vboot_common2_single 11 8192 sha512
-}
-
-# Test a single block algorithm + data algorithm
-function test_vboot_common3_single {
-    local signing_algonum=$1
-    local signing_keylen=$2
-    local signing_hashalgo=$3
-    local data_algonum=$4
-    local data_keylen=$5
-    local data_hashalgo=$6
-
-    echo -e "For ${COL_YELLOW}signing algorithm \
-RSA-${signing_keylen}/${signing_hashalgo}${COL_STOP} \
-and ${COL_YELLOW}data signing algorithm RSA-${data_keylen}/\
-${data_hashalgo}${COL_STOP}"
-    ${TEST_DIR}/vboot_common3_tests \
-        $signing_algonum $data_algonum \
-        ${TESTKEY_DIR}/key_rsa${signing_keylen}.pem \
-        ${TESTKEY_DIR}/key_rsa${signing_keylen}.keyb \
-        ${TESTKEY_DIR}/key_rsa${data_keylen}.pem \
-        ${TESTKEY_DIR}/key_rsa${data_keylen}.keyb
-    if [ $? -ne 0 ]
-    then
-        return_code=255
-    fi
-}
-
-# Test all combinations of key block signing algorithm and data signing
-# algorithm
-function test_vboot_common3_all {
-  signing_algorithmcounter=0
-  data_algorithmcounter=0
-  for signing_keylen in ${key_lengths[@]}
-  do
-    for signing_hashalgo in ${hash_algos[@]}
-    do
-      let data_algorithmcounter=0
-      for data_keylen in ${key_lengths[@]}
-      do
-        for data_hashalgo in ${hash_algos[@]}
-        do
-            test_vboot_common3_single \
-                $signing_algorithmcounter $signing_keylen $signing_hashalgo \
-                $data_algorithmcounter $data_keylen $data_hashalgo
-            let data_algorithmcounter=data_algorithmcounter+1
-        done
-      done
-      let signing_algorithmcounter=signing_algorithmcounter+1
-    done
-  done
-}
-
-# Test only the combinations of key block signing algorithm and data signing
-# algorithm that we actually use
-function test_vboot_common3 {
-    test_vboot_common3_single 7 4096 sha256 4 2048 sha256
-    test_vboot_common3_single 11 8192 sha512 4 2048 sha256
-    test_vboot_common3_single 11 8192 sha512 7 4096 sha256
-}
-
-check_test_keys
-echo
-echo "Testing vboot_common tests which don't depend on keys..."
-test_vboot_common
-
-echo
-echo "Testing vboot_common tests which depend on one key..."
-if [ "$1" == "--all" ] ; then
-    test_vboot_common2_all
-else
-    test_vboot_common2
-fi
-
-echo
-echo "Testing vboot_common tests which depend on two keys..."
-if [ "$1" == "--all" ] ; then
-    test_vboot_common3_all
-else
-    test_vboot_common3
-fi
-
-exit $return_code
diff --git a/tests/vb2_common2_tests.c b/tests/vb2_common2_tests.c
new file mode 100644
index 0000000..cd962a7
--- /dev/null
+++ b/tests/vb2_common2_tests.c
@@ -0,0 +1,209 @@
+/* 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 firmware image library.
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "file_keys.h"
+#include "host_common.h"
+#include "vboot_common.h"
+#include "test_common.h"
+
+#include "2common.h"
+#include "2rsa.h"
+
+static void test_unpack_key(const VbPublicKey *orig_key)
+{
+	struct vb2_public_key rsa;
+	VbPublicKey *key = PublicKeyAlloc(orig_key->key_size, 0, 0);
+
+	/* vb2_packed_key and VbPublicKey are bit-identical */
+	struct vb2_packed_key *key2 = (struct vb2_packed_key *)key;
+	uint8_t *buf = (uint8_t *)key;
+
+	/*
+	 * Key data follows the header for a newly allocated key, so we can
+	 * calculate the buffer size by looking at how far the key data goes.
+	 */
+	uint32_t size = key2->key_offset + key2->key_size;
+
+	PublicKeyCopy(key, orig_key);
+	TEST_EQ(vb2_unpack_key(&rsa, buf, size),
+		0, "vb2_unpack_key() ok");
+
+	TEST_EQ(rsa.algorithm, key2->algorithm, "vb2_unpack_key() algorithm");
+
+	PublicKeyCopy(key, orig_key);
+	key2->algorithm = VB2_ALG_COUNT;
+	TEST_NEQ(vb2_unpack_key(&rsa, buf, size),
+		 0, "vb2_unpack_key() invalid algorithm");
+
+	PublicKeyCopy(key, orig_key);
+	key2->key_size--;
+	TEST_NEQ(vb2_unpack_key(&rsa, buf, size),
+		 0, "vb2_unpack_key() invalid size");
+	key2->key_size++;
+
+	PublicKeyCopy(key, orig_key);
+	key2->key_offset++;
+	TEST_NEQ(vb2_unpack_key(&rsa, buf, size + 1),
+		 0, "vb2_unpack_key() unaligned data");
+	key2->key_offset--;
+
+	PublicKeyCopy(key, orig_key);
+	*(uint32_t *)(buf + key2->key_offset) /= 2;
+	TEST_NEQ(vb2_unpack_key(&rsa, buf, size),
+		 0, "vb2_unpack_key() invalid key array size");
+
+	PublicKeyCopy(key, orig_key);
+	TEST_NEQ(vb2_unpack_key(&rsa, buf, size - 1),
+		 0, "vb2_unpack_key() buffer too small");
+
+	PublicKeyCopy(key, orig_key);
+	TEST_EQ(vb2_unpack_key(&rsa, buf, size),
+		0, "vb2_unpack_key() ok2");
+
+	free(key);
+}
+
+static void test_verify_data(const VbPublicKey *public_key,
+			     const VbPrivateKey *private_key)
+{
+	const uint8_t test_data[] = "This is some test data to sign.";
+	const uint64_t test_size = sizeof(test_data);
+	uint8_t workbuf[VB2_VERIFY_DATA_WORKBUF_BYTES];
+	struct vb2_workbuf wb;
+	VbSignature *sig;
+
+	struct vb2_public_key rsa;
+	struct vb2_signature *sig2;
+
+	struct vb2_packed_key *public_key2;
+
+	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
+
+	/* Vb2 structs are bit-identical to the old ones */
+	public_key2 = (struct vb2_packed_key *)public_key;
+	uint32_t pubkey_size = public_key2->key_offset + public_key2->key_size;
+
+	/* Calculate good signature */
+	sig = CalculateSignature(test_data, test_size, private_key);
+	TEST_PTR_NEQ(sig, 0, "VerifyData() calculate signature");
+	if (!sig)
+		return;
+
+	/* Allocate signature copy for tests */
+	sig2 = (struct vb2_signature *)
+		SignatureAlloc(siglen_map[public_key2->algorithm], 0);
+
+	TEST_EQ(vb2_unpack_key(&rsa, (uint8_t *)public_key2, pubkey_size),
+		0, "vb2_verify_data() unpack key");
+
+	memcpy(sig2, sig, sizeof(VbSignature) + sig->sig_size);
+	rsa.algorithm += VB2_ALG_COUNT;
+	TEST_NEQ(vb2_verify_data(test_data, test_size, sig2, &rsa,
+				 &wb),
+		 0, "vb2_verify_data() bad key");
+	rsa.algorithm -= VB2_ALG_COUNT;
+
+	vb2_workbuf_init(&wb, workbuf, 4);
+	memcpy(sig2, sig, sizeof(VbSignature) + sig->sig_size);
+	TEST_NEQ(vb2_verify_data(test_data, test_size, sig2, &rsa, &wb),
+		 0, "vb2_verify_data() workbuf too small");
+	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
+
+	memcpy(sig2, sig, sizeof(VbSignature) + sig->sig_size);
+	TEST_EQ(vb2_verify_data(test_data, test_size, sig2, &rsa, &wb),
+		0, "vb2_verify_data() ok");
+
+	memcpy(sig2, sig, sizeof(VbSignature) + sig->sig_size);
+	sig2->sig_size -= 16;
+	TEST_NEQ(vb2_verify_data(test_data, test_size, sig2, &rsa, &wb),
+		 0, "vb2_verify_data() wrong sig size");
+
+	memcpy(sig2, sig, sizeof(VbSignature) + sig->sig_size);
+	TEST_NEQ(vb2_verify_data(test_data, test_size - 1, sig2, &rsa, &wb),
+		 0, "vb2_verify_data() input buffer too small");
+
+	memcpy(sig2, sig, sizeof(VbSignature) + sig->sig_size);
+	vb2_signature_data(sig2)[0] ^= 0x5A;
+	TEST_NEQ(vb2_verify_data(test_data, test_size, sig2, &rsa, &wb),
+		 0, "vb2_verify_data() wrong sig");
+
+	free(sig);
+	free(sig2);
+}
+
+int test_algorithm(int key_algorithm, const char *keys_dir)
+{
+	char filename[1024];
+	int rsa_len = siglen_map[key_algorithm] * 8;
+
+	VbPrivateKey *private_key = NULL;
+	VbPublicKey *public_key = NULL;
+
+	printf("***Testing algorithm: %s\n", algo_strings[key_algorithm]);
+
+	sprintf(filename, "%s/key_rsa%d.pem", keys_dir, rsa_len);
+	private_key = PrivateKeyReadPem(filename, key_algorithm);
+	if (!private_key) {
+		fprintf(stderr, "Error reading private_key: %s\n", filename);
+		return 1;
+	}
+
+	sprintf(filename, "%s/key_rsa%d.keyb", keys_dir, rsa_len);
+	public_key = PublicKeyReadKeyb(filename, key_algorithm, 1);
+	if (!public_key) {
+		fprintf(stderr, "Error reading public_key: %s\n", filename);
+		return 1;
+	}
+
+	test_unpack_key(public_key);
+	test_verify_data(public_key, private_key);
+
+	if (public_key)
+		free(public_key);
+	if (private_key)
+		free(private_key);
+
+	return 0;
+}
+
+/* Test only the algorithms we use */
+const int key_algs[] = {
+	VB2_ALG_RSA2048_SHA256,
+	VB2_ALG_RSA4096_SHA256,
+	VB2_ALG_RSA8192_SHA512,
+};
+
+int main(int argc, char *argv[]) {
+
+	if (argc == 2) {
+		int i;
+
+		for (i = 0; i < ARRAY_SIZE(key_algs); i++) {
+			if (test_algorithm(key_algs[i], argv[1]))
+				return 1;
+		}
+
+	} else if (argc == 3 && !strcasecmp(argv[2], "--all")) {
+		/* Test all the algorithms */
+		int alg;
+
+		for (alg = 0; alg < kNumAlgorithms; alg++) {
+			if (test_algorithm(alg, argv[1]))
+				return 1;
+		}
+
+	} else {
+		fprintf(stderr, "Usage: %s <keys_dir> [--all]", argv[0]);
+		return -1;
+	}
+
+	return gTestSuccess ? 0 : 255;
+}
diff --git a/tests/vb2_common3_tests.c b/tests/vb2_common3_tests.c
new file mode 100644
index 0000000..e0fc3ae
--- /dev/null
+++ b/tests/vb2_common3_tests.c
@@ -0,0 +1,382 @@
+/* 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 firmware image library.
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "file_keys.h"
+#include "host_common.h"
+#include "host_key.h"
+#include "host_keyblock.h"
+#include "host_signature.h"
+#include "vboot_common.h"
+#include "test_common.h"
+
+#include "2common.h"
+#include "2rsa.h"
+
+static void resign_keyblock(struct vb2_keyblock *h, const VbPrivateKey *key)
+{
+	VbSignature *sig =
+		CalculateSignature((const uint8_t *)h,
+				   h->keyblock_signature.data_size, key);
+
+	SignatureCopy((VbSignature *)&h->keyblock_signature, sig);
+	free(sig);
+}
+
+static void test_verify_keyblock(const VbPublicKey *public_key,
+				 const VbPrivateKey *private_key,
+				 const VbPublicKey *data_key)
+{
+	uint8_t workbuf[VB2_KEY_BLOCK_VERIFY_WORKBUF_BYTES];
+	struct vb2_workbuf wb;
+	struct vb2_public_key key;
+	struct vb2_keyblock *hdr;
+	struct vb2_keyblock *h;
+	uint32_t hsize;
+
+	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
+
+	/* Unpack public key */
+	TEST_EQ(vb2_unpack_key(&key, (uint8_t *)public_key,
+			       public_key->key_offset + public_key->key_size),
+		0, "vb2_verify_keyblock public key");
+
+	hdr = (struct vb2_keyblock *)
+		KeyBlockCreate(data_key, private_key, 0x1234);
+	TEST_NEQ((size_t)hdr, 0, "vb2_verify_keyblock() prerequisites");
+	if (!hdr)
+		return;
+	hsize = hdr->keyblock_size;
+	h = (struct vb2_keyblock *)malloc(hsize + 2048);
+
+	Memcpy(h, hdr, hsize);
+	TEST_EQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		0, "vb2_verify_keyblock() ok using key");
+
+	Memcpy(h, hdr, hsize);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize - 1, &key, &wb),
+		 0, "vb2_verify_keyblock() size--");
+
+	Memcpy(h, hdr, hsize);
+	TEST_EQ(vb2_verify_keyblock(h, hsize + 1, &key, &wb),
+		0, "vb2_verify_keyblock() size++");
+
+	Memcpy(h, hdr, hsize);
+	h->magic[0] &= 0x12;
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() magic");
+
+	/* Care about major version but not minor */
+	Memcpy(h, hdr, hsize);
+	h->header_version_major++;
+	resign_keyblock(h, private_key);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() major++");
+
+	Memcpy(h, hdr, hsize);
+	h->header_version_major--;
+	resign_keyblock(h, private_key);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() major--");
+
+	Memcpy(h, hdr, hsize);
+	h->header_version_minor++;
+	resign_keyblock(h, private_key);
+	TEST_EQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		0, "vb2_verify_keyblock() minor++");
+
+	Memcpy(h, hdr, hsize);
+	h->header_version_minor--;
+	resign_keyblock(h, private_key);
+	TEST_EQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		0, "vb2_verify_keyblock() minor--");
+
+	/* Check signature */
+	Memcpy(h, hdr, hsize);
+	h->keyblock_signature.sig_offset = hsize;
+	resign_keyblock(h, private_key);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() sig off end");
+
+	Memcpy(h, hdr, hsize);
+	h->keyblock_signature.sig_size--;
+	resign_keyblock(h, private_key);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() sig too small");
+
+	Memcpy(h, hdr, hsize);
+	((uint8_t *)vb2_packed_key_data(&h->data_key))[0] ^= 0x34;
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() sig mismatch");
+
+	Memcpy(h, hdr, hsize);
+	h->keyblock_signature.data_size = h->keyblock_size + 1;
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() sig data past end of block");
+
+	/* Check that we signed header and data key */
+	Memcpy(h, hdr, hsize);
+	h->keyblock_signature.data_size = 4;
+	h->data_key.key_offset = 0;
+	h->data_key.key_size = 0;
+	resign_keyblock(h, private_key);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() didn't sign header");
+
+	Memcpy(h, hdr, hsize);
+	h->data_key.key_offset = hsize;
+	resign_keyblock(h, private_key);
+	TEST_NEQ(vb2_verify_keyblock(h, hsize, &key, &wb),
+		 0, "vb2_verify_keyblock() data key off end");
+
+	/* Corner cases for error checking */
+	TEST_NEQ(vb2_verify_keyblock(NULL, 4, &key, &wb),
+		 0, "vb2_verify_keyblock size too small");
+
+	/*
+	 * TODO: verify parser can support a bigger header (i.e., one where
+	 * data_key.key_offset is bigger than expected).
+	 */
+
+	free(h);
+	free(hdr);
+}
+
+static void resign_fw_preamble(struct vb2_fw_preamble *h,
+			       const VbPrivateKey *key)
+{
+	VbSignature *sig = CalculateSignature(
+		(const uint8_t *)h, h->preamble_signature.data_size, key);
+
+	SignatureCopy((VbSignature *)&h->preamble_signature, sig);
+	free(sig);
+}
+
+static void test_verify_fw_preamble(const VbPublicKey *public_key,
+				    const VbPrivateKey *private_key,
+				    const VbPublicKey *kernel_subkey)
+{
+	struct vb2_fw_preamble *hdr;
+	struct vb2_fw_preamble *h;
+	struct vb2_public_key rsa;
+	uint8_t workbuf[VB2_VERIFY_FIRMWARE_PREAMBLE_WORKBUF_BYTES];
+	struct vb2_workbuf wb;
+	uint32_t hsize;
+
+	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
+
+	/* Create a dummy signature */
+	VbSignature *body_sig = SignatureAlloc(56, 78);
+
+	TEST_EQ(vb2_unpack_key(&rsa, (uint8_t *)public_key,
+			       public_key->key_offset + public_key->key_size),
+		0, "vb2_verify_fw_preamble() prereq key");
+
+	hdr = (struct vb2_fw_preamble *)
+		CreateFirmwarePreamble(0x1234, kernel_subkey, body_sig,
+				       private_key, 0x5678);
+	TEST_PTR_NEQ(hdr, NULL,
+		     "VerifyFirmwarePreamble() prereq test preamble");
+	if (!hdr)
+		return;
+	hsize = (uint32_t) hdr->preamble_size;
+	h = (struct vb2_fw_preamble *)malloc(hsize + 16384);
+
+	Memcpy(h, hdr, hsize);
+	TEST_EQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		0, "vb2_verify_fw_preamble() ok using key");
+
+	Memcpy(h, hdr, hsize);
+	TEST_NEQ(vb2_verify_fw_preamble(h, 4, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() size tiny");
+
+	Memcpy(h, hdr, hsize);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize - 1, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() size--");
+
+	Memcpy(h, hdr, hsize);
+	TEST_EQ(vb2_verify_fw_preamble(h, hsize + 1, &rsa, &wb),
+		0, "vb2_verify_fw_preamble() size++");
+
+	/* Care about major version but not minor */
+	Memcpy(h, hdr, hsize);
+	h->header_version_major++;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() major++");
+
+	Memcpy(h, hdr, hsize);
+	h->header_version_major--;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() major--");
+
+	Memcpy(h, hdr, hsize);
+	h->header_version_minor++;
+	resign_fw_preamble(h, private_key);
+	TEST_EQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		0, "vb2_verify_fw_preamble() minor++");
+
+	Memcpy(h, hdr, hsize);
+	h->header_version_minor--;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() 2.0 not supported");
+
+	/* Check signature */
+	Memcpy(h, hdr, hsize);
+	h->preamble_signature.sig_offset = hsize;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() sig off end");
+
+	Memcpy(h, hdr, hsize);
+	h->preamble_signature.sig_size--;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() sig too small");
+
+	Memcpy(h, hdr, hsize);
+	((uint8_t *)vb2_packed_key_data(&h->kernel_subkey))[0] ^= 0x34;
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() sig mismatch");
+
+	/* Check that we signed header, kernel subkey, and body sig */
+	Memcpy(h, hdr, hsize);
+	h->preamble_signature.data_size = 4;
+	h->kernel_subkey.key_offset = 0;
+	h->kernel_subkey.key_size = 0;
+	h->body_signature.sig_offset = 0;
+	h->body_signature.sig_size = 0;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() didn't sign header");
+
+	Memcpy(h, hdr, hsize);
+	h->kernel_subkey.key_offset = hsize;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() kernel subkey off end");
+
+	Memcpy(h, hdr, hsize);
+	h->body_signature.sig_offset = hsize;
+	resign_fw_preamble(h, private_key);
+	TEST_NEQ(vb2_verify_fw_preamble(h, hsize, &rsa, &wb),
+		 0, "vb2_verify_fw_preamble() body sig off end");
+
+	/* TODO: verify with extra padding at end of header. */
+
+	free(h);
+	free(hdr);
+}
+
+int test_permutation(int signing_key_algorithm, int data_key_algorithm,
+		     const char *keys_dir)
+{
+	char filename[1024];
+	int signing_rsa_len = siglen_map[signing_key_algorithm] * 8;
+	int data_rsa_len = siglen_map[data_key_algorithm] * 8;
+
+	VbPrivateKey *signing_private_key = NULL;
+	VbPublicKey *signing_public_key = NULL;
+	VbPublicKey *data_public_key = NULL;
+
+	printf("***Testing signing algorithm: %s\n",
+	       algo_strings[signing_key_algorithm]);
+	printf("***With data key algorithm: %s\n",
+	       algo_strings[data_key_algorithm]);
+
+	sprintf(filename, "%s/key_rsa%d.pem", keys_dir, signing_rsa_len);
+	signing_private_key = PrivateKeyReadPem(filename,
+						signing_key_algorithm);
+	if (!signing_private_key) {
+		fprintf(stderr, "Error reading signing_private_key: %s\n",
+			filename);
+		return 1;
+	}
+
+	sprintf(filename, "%s/key_rsa%d.keyb", keys_dir, signing_rsa_len);
+	signing_public_key = PublicKeyReadKeyb(filename,
+					       signing_key_algorithm, 1);
+	if (!signing_public_key) {
+		fprintf(stderr, "Error reading signing_public_key: %s\n",
+			filename);
+		return 1;
+	}
+
+	sprintf(filename, "%s/key_rsa%d.keyb", keys_dir, data_rsa_len);
+	data_public_key = PublicKeyReadKeyb(filename,
+					    data_key_algorithm, 1);
+	if (!data_public_key) {
+		fprintf(stderr, "Error reading data_public_key: %s\n",
+			filename);
+		return 1;
+	}
+
+	test_verify_keyblock(signing_public_key, signing_private_key,
+			     data_public_key);
+	test_verify_fw_preamble(signing_public_key, signing_private_key,
+				data_public_key);
+
+	if (signing_public_key)
+		free(signing_public_key);
+	if (signing_private_key)
+		free(signing_private_key);
+	if (data_public_key)
+		free(data_public_key);
+
+	return 0;
+}
+
+struct test_perm
+{
+	int signing_algorithm;
+	int data_key_algorithm;
+};
+
+/* Permutations of signing and data key algorithms in active use */
+const struct test_perm test_perms[] = {
+	{VB2_ALG_RSA4096_SHA256, VB2_ALG_RSA2048_SHA256},
+	{VB2_ALG_RSA8192_SHA512, VB2_ALG_RSA2048_SHA256},
+	{VB2_ALG_RSA8192_SHA512, VB2_ALG_RSA4096_SHA256},
+};
+
+int main(int argc, char *argv[])
+{
+	if (argc == 2) {
+		/* Test only the algorithms we use */
+		int i;
+
+		for (i = 0; i < ARRAY_SIZE(test_perms); i++) {
+			if (test_permutation(test_perms[i].signing_algorithm,
+					     test_perms[i].data_key_algorithm,
+					     argv[1]))
+				return 1;
+		}
+
+	} else if (argc == 3 && !strcasecmp(argv[2], "--all")) {
+		/* Test all the algorithms */
+		int sign_alg, data_alg;
+
+		for (sign_alg = 0; sign_alg < VB2_ALG_COUNT; sign_alg++) {
+			for (data_alg = 0; data_alg < VB2_ALG_COUNT;
+			     data_alg++) {
+				if (test_permutation(sign_alg, data_alg,
+						     argv[1]))
+					return 1;
+			}
+		}
+	} else {
+		fprintf(stderr,	"Usage: %s <keys_dir> [--all]",	argv[0]);
+		return -1;
+	}
+
+	return gTestSuccess ? 0 : 255;
+}
diff --git a/tests/vb2_common_tests.c b/tests/vb2_common_tests.c
index 123de81..fd8a7ac 100644
--- a/tests/vb2_common_tests.c
+++ b/tests/vb2_common_tests.c
@@ -93,10 +93,134 @@
 	TEST_EQ(wb.size, 8, "  size");
 }
 
+/*
+ * Test struct packing for vboot_struct.h structs which are passed between
+ * firmware and OS, or passed between different phases of firmware.
+ */
+static void test_struct_packing(void)
+{
+	TEST_EQ(EXPECTED_VBPUBLICKEY_SIZE, sizeof(struct vb2_packed_key),
+		"sizeof(vb2_packed_key)");
+	TEST_EQ(EXPECTED_VBSIGNATURE_SIZE, sizeof(struct vb2_signature),
+		"sizeof(vb2_signature)");
+	TEST_EQ(EXPECTED_VB2KEYBLOCKHEADER_SIZE,
+		sizeof(struct vb2_keyblock),
+		"sizeof(VbKeyBlockHeader)");
+	TEST_EQ(EXPECTED_VB2FIRMWAREPREAMBLEHEADER2_1_SIZE,
+		sizeof(struct vb2_fw_preamble),
+		"sizeof(vb2_fw_preamble)");
+}
+
+/**
+ * Helper functions not dependent on specific key sizes
+ */
+static void test_helper_functions(void)
+{
+	{
+		uint8_t *p = (uint8_t *)test_helper_functions;
+		TEST_EQ((int)vb2_offset_of(p, p), 0, "vb2_offset_of() equal");
+		TEST_EQ((int)vb2_offset_of(p, p+10), 10,
+			"vb2_offset_of() positive");
+	}
+
+	{
+		struct vb2_packed_key k = {.key_offset = sizeof(k)};
+		TEST_EQ((int)vb2_offset_of(&k, vb2_packed_key_data(&k)),
+			sizeof(k), "vb2_packed_key_data() adjacent");
+	}
+
+	{
+		struct vb2_packed_key k = {.key_offset = 123};
+		TEST_EQ((int)vb2_offset_of(&k, vb2_packed_key_data(&k)), 123,
+			"vb2_packed_key_data() spaced");
+	}
+
+	{
+		struct vb2_signature s = {.sig_offset = sizeof(s)};
+		TEST_EQ((int)vb2_offset_of(&s, vb2_signature_data(&s)),
+			sizeof(s), "vb2_signature_data() adjacent");
+	}
+
+	{
+		struct vb2_signature s = {.sig_offset = 123};
+		TEST_EQ((int)vb2_offset_of(&s, vb2_signature_data(&s)), 123,
+			"vb2_signature_data() spaced");
+	}
+
+	{
+		uint8_t *p = (uint8_t *)test_helper_functions;
+		TEST_EQ(vb2_verify_member_inside(p, 20, p, 6, 11, 3), 0,
+			"MemberInside ok 1");
+		TEST_EQ(vb2_verify_member_inside(p, 20, p+4, 4, 8, 4), 0,
+			"MemberInside ok 2");
+		TEST_NEQ(vb2_verify_member_inside(p, 20, p-4, 4, 8, 4), 0,
+			 "MemberInside member before parent");
+		TEST_NEQ(vb2_verify_member_inside(p, 20, p+20, 4, 8, 4), 0,
+			 "MemberInside member after parent");
+		TEST_NEQ(vb2_verify_member_inside(p, 20, p, 21, 0, 0), 0,
+			 "MemberInside member too big");
+		TEST_NEQ(vb2_verify_member_inside(p, 20, p, 4, 21, 0), 0,
+			 "MemberInside data after parent");
+		TEST_NEQ(vb2_verify_member_inside(p, 20, p, 4, UINT32_MAX, 0),
+			 0, "MemberInside data before parent");
+		TEST_NEQ(vb2_verify_member_inside(p, 20, p, 4, 4, 17), 0,
+			 "MemberInside data too big");
+		TEST_NEQ(vb2_verify_member_inside(p, UINT32_MAX,
+						  p+UINT32_MAX-9, 12, 5, 0), 0,
+			 "MemberInside wraparound 1");
+		TEST_NEQ(vb2_verify_member_inside(p, UINT32_MAX,
+						  p+UINT32_MAX-9, 5, 12, 0), 0,
+			 "MemberInside wraparound 2");
+		TEST_NEQ(vb2_verify_member_inside(p, UINT32_MAX,
+						  p+UINT32_MAX-9, 5, 0, 12), 0,
+			 "MemberInside wraparound 3");
+	}
+
+	{
+		struct vb2_packed_key k = {.key_offset = sizeof(k),
+					   .key_size = 128};
+		TEST_EQ(vb2_verify_packed_key_inside(&k, sizeof(k)+128, &k), 0,
+			"PublicKeyInside ok 1");
+		TEST_EQ(vb2_verify_packed_key_inside(&k - 1,
+						     2*sizeof(k)+128, &k),
+			0, "PublicKeyInside ok 2");
+		TEST_NEQ(vb2_verify_packed_key_inside(&k, 128, &k), 0,
+			 "PublicKeyInside key too big");
+	}
+
+	{
+		struct vb2_packed_key k = {.key_offset = 100,
+					   .key_size = 4};
+		TEST_NEQ(vb2_verify_packed_key_inside(&k, 99, &k), 0,
+			 "PublicKeyInside offset too big");
+	}
+
+	{
+		struct vb2_signature s = {.sig_offset = sizeof(s),
+					  .sig_size = 128};
+		TEST_EQ(vb2_verify_signature_inside(&s, sizeof(s)+128, &s), 0,
+			"SignatureInside ok 1");
+		TEST_EQ(vb2_verify_signature_inside(&s - 1,
+						    2*sizeof(s)+128, &s),
+			0, "SignatureInside ok 2");
+		TEST_NEQ(vb2_verify_signature_inside(&s, 128, &s), 0,
+			 "SignatureInside sig too big");
+	}
+
+	{
+		struct vb2_signature s = {.sig_offset = 100,
+					  .sig_size = 4};
+		TEST_NEQ(vb2_verify_signature_inside(&s, 99, &s), 0,
+			 "SignatureInside offset too big");
+	}
+}
+
 int main(int argc, char* argv[])
 {
 	test_align();
 	test_workbuf();
+	test_struct_packing();
+	test_helper_functions();
 
 	return gTestSuccess ? 0 : 255;
 }