Data structure and interface for manipulating and handing firmware images for verified boot.

Review URL: http://codereview.chromium.org/564020
diff --git a/include/file_keys.h b/include/file_keys.h
new file mode 100644
index 0000000..9236172
--- /dev/null
+++ b/include/file_keys.h
@@ -0,0 +1,28 @@
+/* Copyright (c) 2010 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.
+ *
+ * Utility functions for file and key handling.
+ */
+
+#ifndef VBOOT_REFERENCE_FILE_KEYS_H_
+#define VBOOT_REFERENCE_FILE_KEYS_H_
+
+#include "rsa.h"
+
+/* Read file named [input_file] into a buffer and stores the length into
+ * [len].
+ *
+ * Returns a pointer to the buffer. Caller owns the returned pointer and
+ * must free it.
+ */
+uint8_t* BufferFromFile(char* input_file, int* len);
+
+/* Read a pre-processed RSA Public Key from file [input_file].
+ *
+ * Returns a pointer to the read key. Caller owns the returned pointer and
+ * must free it.
+ */
+RSAPublicKey* RSAPublicKeyFromFile(char* input_file);
+
+#endif  /* VBOOT_REFERENCE_FILE_KEYS_H_ */
diff --git a/include/firmware_image.h b/include/firmware_image.h
new file mode 100644
index 0000000..e2cbb5c
--- /dev/null
+++ b/include/firmware_image.h
@@ -0,0 +1,133 @@
+/* Copyright (c) 2010 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.
+ *
+ * Data structure and API definitions for a verified boot firmware image.
+ */
+
+#ifndef VBOOT_REFERENCE_FIRMWARE_IMAGE_H_
+#define VBOOT_REFERENCE_FIRMWARE_IMAGE_H_
+
+#include <inttypes.h>
+
+#include "rsa.h"
+#include "sha.h"
+
+#define FIRMWARE_MAGIC "CHROMEOS"
+#define FIRMWARE_MAGIC_SIZE 8
+#define FIRMWARE_PREAMBLE_SIZE 8
+
+#define ROOT_SIGNATURE_ALGORITHM 11 /* RSA 8192 and SHA-512. */
+#define ROOT_SIGNATURE_ALGORITHM_STRING "11"
+
+typedef struct FirmwareImage {
+  uint8_t magic[FIRMWARE_MAGIC_SIZE];
+  /* Key Header */
+  uint16_t header_len;  /* Length of the header. */
+  uint16_t sign_algorithm;  /* Signature algorithm used by the signing key. */
+  uint8_t* sign_key;  /* Pre-processed public half of signing key. */
+  uint16_t key_version;  /* Key Version# for preventing rollbacks. */
+  uint8_t header_hash[SHA512_DIGEST_SIZE];  /* SHA-512 hash of the header.*/
+
+  uint8_t key_signature[RSA8192NUMBYTES];   /* Signature of the header above. */
+
+  /* Firmware Preamble. */
+  uint16_t firmware_version;  /* Firmware Version# for preventing rollbacks.*/
+  uint32_t firmware_len;  /* Length of the rest of the R/W firmware data. */
+  uint8_t preamble[FIRMWARE_PREAMBLE_SIZE];  /* Remaining preamble data.*/
+
+  uint8_t* preamble_signature;  /* Signature over the preamble. */
+
+  /* The firmware signature comes first as it may allow us to parallelize
+   * the firmware data fetch and RSA public operation.
+   */
+  uint8_t* firmware_signature;  /* Signature on [firmware_data]. */
+  uint8_t* firmware_data;  /* Rest of firmware data */
+
+} FirmwareImage;
+
+/* Allocate and return a new FirmwareImage structure. */
+FirmwareImage* FirmwareImageNew(void);
+
+/* Deep free the contents of [fw]. */
+void FirmwareImageFree(FirmwareImage* fw);
+
+/* Read firmware data from file named [input_file] into [image].
+ *
+ * Returns a filled up FirmwareImage on success, NULL on error.
+ */
+FirmwareImage* ReadFirmware(const char* input_file,
+                             FirmwareImage* image);
+
+/* Write firmware header from [image] to an open file pointed by the
+ * file descriptor [fd].
+ */
+void WriteFirmwareHeader(int fd, FirmwareImage* image);
+
+/* Write firmware preamble from [image] to an open file pointed by the
+ * file descriptor [fd].
+ */
+void WriteFirmwarePreamble(int fd, FirmwareImage* image);
+
+
+/* Write firmware data from [image] into a file named [input_file].
+ *
+ * Return [image] on success, NULL on error.
+ */
+FirmwareImage* WriteFirmware(const char* input_file,
+                             FirmwareImage* image);
+
+/* Pretty print the contents of [image]. Only headers and metadata information
+ * is printed.
+ */
+void PrintFirmware(const FirmwareImage* image);
+
+/* Performs a chained verify of the firmware [image]. If [dev_mode] is
+ * 0 (inactive), then the [root_key] is used to verify the signature of
+ * the signing key, else the check is skipped.
+ *
+ * Returns 0 on success, error code on failure.
+ */
+int VerifyFirmware(const RSAPublicKey* root_key,
+                   const FirmwareImage* image,
+                   const int dev_mode);
+
+/* Error Codes for VerifyFirmware. */
+#define VERIFY_SUCCESS 0
+#define VERIFY_INVALID_IMAGE 1
+#define VERIFY_ROOT_SIGNATURE_FAILED 2
+#define VERIFY_INVALID_ALGORITHM 3
+#define VERIFY_PREAMBLE_SIGNATURE_FAILED 4
+#define VERIFY_FIRMWARE_SIGNATURE_FAILED 5
+#define VERIFY_MAX 6  /* Generic catch-all. */
+
+char* kVerifyFirmwareErrors[VERIFY_MAX];
+
+/* Maps error codes from VerifyFirmware() to error description. */
+char* VerifyErrorString(int error);
+
+
+/* Helper function to invoke external program to calculate signature on
+ * [input_file] using private key [key_file] and signature algorithm
+ * [algorithm].
+ *
+ * Returns the signature. Caller owns the buffer and must Free() it.
+ */
+uint8_t* SignatureFile(char* input_fie, char* key_file, int algorithm);
+
+/* Add a root key signature to the key header to a firmware image [image]
+ * using the private root key in file [root_key_file].
+ *
+ * Return 1 on success, 0 on failure.
+ */
+int AddKeySignature(FirmwareImage* image, char* root_key_file);
+
+/* Add firmware and preamble signature to a firmware image [image]
+ * using the private signing key in file [signing_key_file].
+ *
+ * Return 1 on success, 0 on failure.
+ */
+int AddFirmwareSignature(FirmwareImage* image, char* signing_key_file,
+                         int algorithm);
+
+#endif  /* VBOOT_REFERENCE_FIRMWARE_IMAGE_H_ */
diff --git a/tests/Makefile b/tests/Makefile
index 04df8b1..4801dc5 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -7,15 +7,19 @@
 INCLUDES ?= -I../include/
 TOP ?= ../
 
-LIBS = $(TOP)/crypto/libcrypto.a $(TOP)/common/libcommon.a -lrt
+LIBS = $(TOP)/utils/firmware_image.o $(TOP)/crypto/libcrypto.a $(TOP)/common/libcommon.a  \
+	$(TOP)/utils/file_keys.o -lrt
 
-tests: sha_tests sha_benchmark
+tests: firmware_image_tests sha_tests sha_benchmark
 
 sha_tests: sha_tests.c
-	$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) $< -o $@ $(LIBS)
+	$(CC) $(CFLAGS) $(INCLUDES) $< -o $@ $(LIBS)
+
+firmware_image_tests: firmware_image_tests.c
+	$(CC) $(CFLAGS) $(INCLUDES) $< -o $@ $(LIBS)
 
 sha_benchmark:	sha_benchmark.c timer_utils.c
 	$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) $^ -o $@ $(LIBS)
 
 clean:
-	rm -f sha_tests sha_benchmark
+	rm -f sha_tests sha_benchmark firmware_image_tests
diff --git a/tests/firmware_image_tests.c b/tests/firmware_image_tests.c
new file mode 100644
index 0000000..db44f2e
--- /dev/null
+++ b/tests/firmware_image_tests.c
@@ -0,0 +1,178 @@
+/* Copyright (c) 2010 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 <stdio.h>
+#include <stdlib.h>
+
+#include "file_keys.h"
+#include "firmware_image.h"
+#include "rsa_utility.h"
+#include "sha_utility.h"
+#include "utility.h"
+
+int TEST_EQ(int result, int expected_result, char* testname) {
+  if (result == expected_result) {
+    fprintf(stderr, "%s Test \e[1;32mSUCCEEDED\e[m\n", testname);
+    return 1;
+  }
+  else {
+    fprintf(stderr, "%s Test \e[0;31mFAILED\e[m\n", testname);
+    return 0;
+  }
+}
+
+FirmwareImage* GenerateTestFirmwareImage(int algorithm,
+                                         uint8_t* sign_key,
+                                         int key_version,
+                                         int firmware_version,
+                                         int firmware_len) {
+  FirmwareImage* image = FirmwareImageNew();
+  uint8_t* header_hash;
+  DigestContext ctx;
+
+  Memcpy(image->magic, FIRMWARE_MAGIC, FIRMWARE_MAGIC_SIZE);
+  image->sign_algorithm = algorithm;
+  image->sign_key = (uint8_t*) Malloc(
+      RSAProcessedKeySize(image->sign_algorithm));
+  Memcpy(image->sign_key, sign_key, RSAProcessedKeySize(image->sign_algorithm));
+  image->key_version = key_version;
+
+  /* Calculate SHA-512 digest on header and populate header_hash. */
+  DigestInit(&ctx, ROOT_SIGNATURE_ALGORITHM);
+  DigestUpdate(&ctx, (uint8_t*) &image->header_len,
+               sizeof(image->header_len));
+  DigestUpdate(&ctx, (uint8_t*) &image->sign_algorithm,
+               sizeof(image->sign_algorithm));
+  DigestUpdate(&ctx, image->sign_key,
+               RSAProcessedKeySize(image->sign_algorithm));
+  DigestUpdate(&ctx, (uint8_t*) &image->key_version,
+               sizeof(image->key_version));
+  header_hash = DigestFinal(&ctx);
+  Memcpy(image->header_hash, header_hash, SHA512_DIGEST_SIZE);
+  Free(header_hash);
+
+  /* Update correct header length. */
+  image->header_len = (sizeof(image->header_len) +
+                       sizeof(image->sign_algorithm) +
+                       RSAProcessedKeySize(image->sign_algorithm) +
+                       sizeof(image->key_version) +
+                       sizeof(image->header_hash));
+
+  /* Populate firmware and preamble with dummy data. */
+  image->firmware_version = firmware_version;
+  image->firmware_len = firmware_len;
+  image->preamble_signature = image->firmware_signature = NULL;
+  Memset(image->preamble, 'P', FIRMWARE_PREAMBLE_SIZE);
+  image->firmware_data = Malloc(image->firmware_len);
+  Memset(image->firmware_data, 'F', image->firmware_len);
+
+  return image;
+}
+
+#define DEV_MODE_ENABLED 1
+#define DEV_MODE_DISABLED 0
+
+/* Normal Firmware Verification Tests. */
+int VerifyFirmwareTest(FirmwareImage* image, RSAPublicKey* root_key) {
+  int success = 1;
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_ENABLED),
+               VERIFY_SUCCESS,
+               "Normal Verification (Dev Mode)"))
+    success = 0;
+
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_DISABLED),
+               VERIFY_SUCCESS,
+               "Normal Verification (Trusted)"))
+    success = 0;
+  return success;
+}
+
+/* Tampered Firmware Verification Tests. */
+int VerifyFirmwareTamperTest(FirmwareImage* image, RSAPublicKey* root_key) {
+  int success = 1;
+  fprintf(stderr, "Tampering with firmware preamble....\n");
+  image->firmware_version = 0;
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_ENABLED),
+               VERIFY_PREAMBLE_SIGNATURE_FAILED,
+               "Firmware Preamble Tamper Verification (Dev Mode)"))
+    success = 0;
+
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_DISABLED),
+               VERIFY_PREAMBLE_SIGNATURE_FAILED,
+               "Firmware Preamble Tamper Verification (Trusted)"))
+    success = 0;
+  image->firmware_version = 1;
+
+  image->firmware_data[0] = 'T';
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_ENABLED),
+               VERIFY_FIRMWARE_SIGNATURE_FAILED,
+               "Firmware Tamper Verification (Dev Mode)"))
+    success = 0;
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_DISABLED),
+               VERIFY_FIRMWARE_SIGNATURE_FAILED,
+               "Firmware Tamper Verification (Trusted)"))
+    success = 0;
+  image->firmware_data[0] = 'F';
+
+
+  fprintf(stderr, "Tampering with root key signature...\n");
+  image->key_signature[0] = 0xFF;
+  image->key_signature[1] = 0x00;
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_ENABLED),
+               VERIFY_SUCCESS,
+               "Root Signature Tamper Verification (Dev Mode)"))
+    success = 0;
+  if (!TEST_EQ(VerifyFirmware(root_key, image, DEV_MODE_DISABLED),
+               VERIFY_ROOT_SIGNATURE_FAILED,
+               "Root Signature Tamper Verification (Trusted)"))
+    success = 0;
+
+  return success;
+}
+
+int main(int argc, char* argv[]) {
+  int len;
+  uint8_t* sign_key_buf;
+  FirmwareImage* image;
+  RSAPublicKey* root_key;
+  int success = 1;
+
+  if(argc != 6) {
+    fprintf(stderr, "Usage: %s <algorithm> <root key> <processed root pubkey>"
+            " <signing key> <processed signing key>\n", argv[0]);
+    return -1;
+  }
+
+  /* Read verification keys and create a test image. */
+  root_key = RSAPublicKeyFromFile(argv[3]);
+  sign_key_buf = BufferFromFile(argv[5], &len);
+  image = GenerateTestFirmwareImage(atoi(argv[1]), sign_key_buf, 1,
+                                    1, 1000);
+
+  /* Generate and populate signatures. */
+  if (!AddKeySignature(image, argv[2])) {
+    fprintf(stderr, "Couldn't create key signature.\n");
+    return -1;
+  }
+
+  if (!AddFirmwareSignature(image, argv[4], image->sign_algorithm)) {
+    fprintf(stderr, "Couldn't create firmware and preamble signature.\n");
+    return -1;
+  }
+
+  if (!VerifyFirmwareTest(image, root_key))
+    success = 0;
+  if (!VerifyFirmwareTamperTest(image, root_key))
+    success = 0;
+
+  /* Clean up. */
+  Free(root_key);
+  Free(sign_key_buf);
+  Free(image);
+
+  return !success;
+}
diff --git a/tests/run_rsa_tests.sh b/tests/run_rsa_tests.sh
index 3abadb6..d56f5a0 100755
--- a/tests/run_rsa_tests.sh
+++ b/tests/run_rsa_tests.sh
@@ -48,6 +48,21 @@
   done
 }
 
+function test_verification {
+  algorithmcounter=0
+  for keylen in ${key_lengths[@]}
+  do
+    for hashalgo in ${hash_algos[@]}
+    do
+      echo -e "For ${COL_YELLOW}RSA-$keylen and $hashalgo${COL_STOP}:"
+      cd ${UTIL_DIR} && ${TEST_DIR}/firmware_image_tests $algorithmcounter testkeys/key_rsa8192.pem \
+        testkeys/key_rsa8192.keyb testkeys/key_rsa${keylen}.pem \
+        testkeys/key_rsa${keylen}.keyb
+      let algorithmcounter=algorithmcounter+1
+    done
+  done
+}
+
 function pre_work {
   # Generate a file with random bytes for signature tests.
   echo "Generating test file..."
@@ -81,8 +96,12 @@
 test_signatures
 
 echo
+echo "Testing high-level image verification..."
+test_verification
+
+echo
 echo "Cleaning up..."
-cleanup
+#cleanup
 
 exit $return_code
 
diff --git a/utils/Makefile b/utils/Makefile
index d72aaf4..b13bc65 100644
--- a/utils/Makefile
+++ b/utils/Makefile
@@ -2,19 +2,34 @@
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
+CC ?= gcc
+CFLAGS=-Wall -ggdb
+INCLUDES ?= -I../include/
+TOP ?= ../
+
+
 LIBS=-lcrypto
 FIRMWARELIBS=$(TOP)/crypto/libcrypto.a $(TOP)/common/libcommon.a
 
-all:	dumpRSAPublicKey verify_data signature_digest
+all:	dumpRSAPublicKey verify_data signature_digest firmware_utility
 
 dumpRSAPublicKey:	dumpRSAPublicKey.c
 		$(CC) $(CFLAGS) $(LIBS) $< -o $@
 
-verify_data:	verify_data.c
-	$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) $< -o $@ $(FIRMWARELIBS)
+verify_data:	verify_data.c file_keys.o
+	$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) $< -o $@ file_keys.o $(FIRMWARELIBS) 
 
 signature_digest:	signature_digest.c
 	$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) $< -o $@ $(FIRMWARELIBS)
 
+firmware_utility:	firmware_utility.c firmware_image.o file_keys.o
+	$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) $< -o $@  firmware_image.o $(FIRMWARELIBS)
+
+file_keys.o:	file_keys.c
+		$(CC) $(CFLAGS) -DNDEBUG $(INCLUDES) -c $< -o $@
+
+firmware_image.o:	firmware_image.c
+		$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@
 clean:
-	rm -f dumpRSAPublicKey verify_data signature_digest
+	rm -f dumpRSAPublicKey verify_data signature_digest firmware_image.o file_keys.o
+
diff --git a/utils/file_keys.c b/utils/file_keys.c
new file mode 100644
index 0000000..8a8a2cb
--- /dev/null
+++ b/utils/file_keys.c
@@ -0,0 +1,57 @@
+/* Copyright (c) 2010 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.
+ *
+ * Utility functions for file and key handling.
+ */
+
+#include "file_keys.h"
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "rsa_utility.h"
+#include "utility.h"
+
+uint8_t* BufferFromFile(char* input_file, int* len) {
+  int fd;
+  struct stat stat_fd;
+  uint8_t* buf = NULL;
+
+  if ((fd = open(input_file, O_RDONLY)) == -1) {
+    fprintf(stderr, "Couldn't open file.\n");
+    return NULL;
+  }
+
+  if (-1 == fstat(fd, &stat_fd)) {
+    fprintf(stderr, "Couldn't stat key file\n");
+    return NULL;
+  }
+  *len = stat_fd.st_size;
+
+  /* Read entire key binary blob into a buffer. */
+  buf = (uint8_t*) Malloc(*len);
+  if (!buf)
+    return NULL;
+
+  if (*len != read(fd, buf, *len)) {
+    fprintf(stderr, "Couldn't read key into a buffer.\n");
+    return NULL;
+  }
+
+  close(fd);
+  return buf;
+}
+
+RSAPublicKey* RSAPublicKeyFromFile(char* input_file) {
+  int len;
+  uint8_t* buf = BufferFromFile(input_file, &len);
+  RSAPublicKey* key = RSAPublicKeyFromBuf(buf, len);
+  Free(buf);
+  return key;
+}
diff --git a/utils/firmware_image.c b/utils/firmware_image.c
new file mode 100644
index 0000000..ae89490
--- /dev/null
+++ b/utils/firmware_image.c
@@ -0,0 +1,404 @@
+/* Copyright (c) 2010 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.
+ *
+ * Functions for generating and manipulating a verified boot firmware image.
+ */
+
+#include "firmware_image.h"
+
+#include <fcntl.h>
+#include <limits.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "padding.h"
+#include "rsa_utility.h"
+#include "sha_utility.h"
+#include "utility.h"
+
+
+FirmwareImage* FirmwareImageNew(void) {
+  FirmwareImage* fw = (FirmwareImage*) Malloc(sizeof(FirmwareImage));
+  return fw;
+}
+
+void FirmwareImageFree(FirmwareImage* image) {
+  Free(image->sign_key);
+  Free(image->key_signature);
+  Free(image->preamble_signature);
+  Free(image->firmware_signature);
+  Free(image->firmware_data);
+}
+
+
+FirmwareImage* ReadFirmware(const char* input_file,
+                            FirmwareImage* image) {
+  int fd;
+  struct stat fd_stat;
+
+  int image_len = 0;  /* Total size of the firmware image. */
+  int header_len = 0;
+  int sign_key_len;
+  int signature_len;
+  uint8_t* firmware_buf;
+  MemcpyState st;
+
+  if (!image)
+    return NULL;
+
+  if (-1 == (fd = open(input_file, O_RDONLY))) {
+    fprintf(stderr, "Couldn't open file for reading.\n");
+    return NULL;
+  }
+
+  if (-1 == fstat(fd, &fd_stat)) {
+    fprintf(stderr, "Couldn't stat file.\n");
+    close(fd);
+    return NULL;
+  }
+
+  firmware_buf = (uint8_t*) Malloc(fd_stat.st_size);
+  image_len = fd_stat.st_size;
+
+  /* Read entire file into a buffer. */
+  if (image_len != read(fd, firmware_buf, image_len)) {
+    fprintf(stderr, "Couldn't read file data.\n");
+    close(fd);
+    return NULL;
+  }
+  close(fd);
+
+  st.remaining_len = image_len;
+  st.remaining_buf = firmware_buf;
+
+  /* Read and compare magic bytes. */
+  if (!StatefulMemcpy(&st, &image->magic, FIRMWARE_MAGIC_SIZE))
+    goto parse_failure;
+
+  if (!SafeMemcmp(image->magic, FIRMWARE_MAGIC, FIRMWARE_MAGIC_SIZE)) {
+    fprintf(stderr, "Wrong Firmware Magic.\n");
+    goto parse_failure;
+  }
+
+  StatefulMemcpy(&st, &image->header_len, sizeof(image->header_len));
+  StatefulMemcpy(&st, &image->sign_algorithm, sizeof(image->sign_algorithm));
+
+  /* Valid Algorithm? */
+  if (image->sign_algorithm > kNumAlgorithms)
+    goto parse_failure;
+
+  /* Compute size of pre-processed RSA public key and signature. */
+  sign_key_len = (2*siglen_map[image->sign_algorithm]*sizeof(uint32_t)
+                     + sizeof(uint32_t) + sizeof(int));
+  signature_len = siglen_map[image->sign_algorithm] * sizeof(uint32_t);
+
+
+  /* Check whether the header length is correct. */
+  header_len = (sizeof(image->header_len) + sizeof(image->sign_algorithm) +
+                sizeof(image->key_version) +
+                sizeof(image->header_hash));
+  if (header_len != image->header_len) {
+    fprintf(stderr, "Header length mismatch.");
+    goto parse_failure;
+  }
+
+  /* Read pre-processed public half of the sign key. */
+  image->sign_key = (uint8_t*) Malloc(sign_key_len);
+  StatefulMemcpy(&st, image->sign_key, sign_key_len);
+  StatefulMemcpy(&st, &image->key_version, sizeof(image->key_version));
+  StatefulMemcpy(&st, image->header_hash, sizeof(image->header_hash));
+
+  /* Read key signature. */
+  StatefulMemcpy(&st, image->key_signature, sizeof(image->key_signature));
+
+  /* Read the firmware preamble. */
+  StatefulMemcpy(&st,&image->firmware_version, sizeof(image->firmware_version));
+  StatefulMemcpy(&st, &image->firmware_len, sizeof(image->firmware_len));
+  StatefulMemcpy(&st, image->preamble, sizeof(image->preamble));
+
+  /* Read firmware preamble signature. */
+  image->preamble_signature = (uint8_t*) Malloc(signature_len);
+  StatefulMemcpy(&st, image->preamble_signature, signature_len);
+
+  image->firmware_signature = (uint8_t*) Malloc(signature_len);
+  StatefulMemcpy(&st, image->firmware_signature, signature_len);
+
+  image->firmware_data = (uint8_t*) Malloc(image->firmware_len);
+  StatefulMemcpy(&st, image->firmware_data, image->firmware_len);
+
+  if(st.remaining_len != 0) /* Overrun or underrun. */
+    goto parse_failure;
+
+  Free(firmware_buf);
+  return image;
+
+parse_failure:
+  Free(firmware_buf);
+  return NULL;
+}
+
+void WriteFirmwareHeader(int fd, FirmwareImage* image) {
+  int sign_key_len;
+  write(fd, &image->header_len, sizeof(image->header_len));
+  write(fd, &image->sign_algorithm, sizeof(image->header_len));
+  sign_key_len = (image->header_len - sizeof(image->header_len) -
+                     sizeof(image->sign_algorithm) -
+                     sizeof(image->key_version) -
+                     sizeof(image->header_hash));
+  write(fd, image->sign_key, sign_key_len);
+  write(fd, &image->key_version, sizeof(image->key_version));
+  write(fd, &image->header_hash, sizeof(image->header_hash));
+}
+
+void WriteFirmwarePreamble(int fd, FirmwareImage* image) {
+  write(fd, &image->firmware_version,
+        sizeof(image->firmware_version));
+  write(fd, &image->firmware_len, sizeof(image->firmware_len));
+  write(fd, image->preamble, sizeof(image->preamble));
+}
+
+
+FirmwareImage* WriteFirmware(const char* input_file,
+                             FirmwareImage* image) {
+   int fd;
+   int signature_len;
+
+   if (!image)
+     return NULL;
+
+   if (-1 == (fd = open(input_file, O_WRONLY))) {
+     fprintf(stderr, "Couldn't open file for writing.\n");
+     return NULL;
+   }
+
+   write(fd, &image->magic, sizeof(image->magic));
+   WriteFirmwareHeader(fd, image);
+   write(fd, image->key_signature, sizeof(image->key_signature));
+   signature_len = siglen_map[image->sign_algorithm] * sizeof(uint32_t);
+   WriteFirmwarePreamble(fd, image);
+   write(fd, image->preamble_signature, signature_len);
+   write(fd, image->firmware_signature, signature_len);
+   write(fd, image->firmware_data, image->firmware_len);
+
+   close(fd);
+   return image;
+}
+
+void PrintFirmware(const FirmwareImage* image) {
+  if (!image)
+    return;
+
+  /* Print header. */
+  printf("Header Length = %d\n"
+         "Algorithm Id = %d\n"
+         "Signature Algorithm = %s\n"
+         "Key Version = %d\n\n",
+         image->header_len,
+         image->sign_algorithm,
+         algo_strings[image->sign_algorithm],
+         image->key_version);
+  /* TODO(gauravsh): Output hash and key signature here? */
+  /* Print preamble. */
+  printf("Firmware Version = %d\n"
+         "Firmware Length = %d\n\n",
+         image->firmware_version,
+         image->firmware_len);
+  /* Output key signature here? */
+}
+
+int VerifyFirmware(const RSAPublicKey* root_key,
+                   const FirmwareImage* image,
+                   const int dev_mode) {
+  RSAPublicKey* sign_key;
+  uint8_t* header_digest = NULL;
+  uint8_t* preamble_digest = NULL;
+  uint8_t* firmware_digest = NULL;
+  int sign_key_size;
+  int signature_size;
+  int error_code = 0;
+  DigestContext ctx;
+
+  if (!image)
+    return VERIFY_INVALID_IMAGE;
+
+  /* Verify root key signature on the sign key header if we
+   * are not in dev mode. */
+  if (!dev_mode) {
+    DigestInit(&ctx, ROOT_SIGNATURE_ALGORITHM);
+    DigestUpdate(&ctx, (uint8_t*) &image->header_len,
+                 sizeof(image->header_len));
+    DigestUpdate(&ctx, (uint8_t*) &image->sign_algorithm,
+                 sizeof(image->sign_algorithm));
+    DigestUpdate(&ctx, image->sign_key,
+                 RSAProcessedKeySize(image->sign_algorithm));
+    DigestUpdate(&ctx, (uint8_t*) &image->key_version,
+                 sizeof(image->key_version));
+    DigestUpdate(&ctx, image->header_hash,
+                 sizeof(image->header_hash));
+    header_digest = DigestFinal(&ctx);
+    if (!RSA_verify(root_key, image->key_signature,
+                    sizeof(image->key_signature),
+                    ROOT_SIGNATURE_ALGORITHM,
+                    header_digest)) {
+      error_code =  VERIFY_ROOT_SIGNATURE_FAILED;
+      goto verify_failure;
+    }
+  }
+
+  /* Get sign key to verify the rest of the firmware. */
+  sign_key_size = RSAProcessedKeySize(image->sign_algorithm);
+  sign_key = RSAPublicKeyFromBuf(image->sign_key,
+                                 sign_key_size);
+  signature_size = siglen_map[image->sign_algorithm] * sizeof(uint32_t);
+
+  if (image->sign_algorithm >= kNumAlgorithms)
+    return VERIFY_INVALID_ALGORITHM;
+
+  /* Verify firmware preamble signature. */
+  DigestInit(&ctx, image->sign_algorithm);
+  DigestUpdate(&ctx, (uint8_t*) &image->firmware_version,
+               sizeof(image->firmware_version));
+  DigestUpdate(&ctx, (uint8_t*) &image->firmware_len,
+               sizeof(image->firmware_len));
+  DigestUpdate(&ctx, (uint8_t*) &image->preamble,
+               sizeof(image->preamble));
+  preamble_digest = DigestFinal(&ctx);
+  if (!RSA_verify(sign_key, image->preamble_signature,
+                  signature_size, image->sign_algorithm,
+                  preamble_digest)) {
+    error_code = VERIFY_PREAMBLE_SIGNATURE_FAILED;
+    goto verify_failure;
+  }
+
+  /* Verify firmware signature. */
+  firmware_digest = DigestBuf(image->firmware_data,
+                              image->firmware_len,
+                              image->sign_algorithm);
+  if(!RSA_verify(sign_key, image->firmware_signature,
+                 signature_size, image->sign_algorithm,
+                 firmware_digest)) {
+    error_code = VERIFY_FIRMWARE_SIGNATURE_FAILED;
+    goto verify_failure;
+  }
+
+verify_failure:
+  Free(firmware_digest);
+  Free(preamble_digest);
+  Free(header_digest);
+  return error_code;
+}
+
+char* kVerifyFirmwareErrors[VERIFY_MAX] = {
+  "Success.",
+  "Invalid Image.",
+  "Root Key Signature Failed.",
+  "Invalid Verification Algorithm.",
+  "Preamble Signature Failed.",
+  "Firmware Signature Failed.",
+};
+
+uint8_t* SignatureFile(char* input_file, char* key_file, int algorithm) {
+  char* sign_utility = "./sign_data.sh";
+  char* cmd;  /* Command line to invoke. */
+  int cmd_len;
+  FILE* cmd_out;  /* File descriptor to command output. */
+  uint8_t* signature = NULL;
+  int signature_size = siglen_map[algorithm] * sizeof(uint32_t);
+
+  /* Build command line:
+   * sign_data.sh <algorithm> <key file> <input file>
+   */
+  cmd_len = (strlen(sign_utility) + 1 + /* +1 for space. */
+             2 + 1 + /* For [algorithm]. */
+             strlen(key_file) + 1 + /* +1 for space. */
+             strlen(input_file) +
+             1);  /* For the trailing '\0'. */
+  cmd = (char*) Malloc(cmd_len);
+  snprintf(cmd, cmd_len, "%s %d %s %s", sign_utility, algorithm, key_file,
+           input_file);
+  cmd_out = popen(cmd, "r");
+  Free(cmd);
+  if (!cmd_out) {
+    fprintf(stderr, "Couldn't execute: %s\n", cmd);
+    return NULL;
+  }
+
+  signature = (uint8_t*) Malloc(signature_size);
+  if (fread(signature, signature_size, 1, cmd_out) != 1) {
+    fprintf(stderr, "Couldn't read signature.\n");
+    pclose(cmd_out);
+    Free(signature);
+    return NULL;
+  }
+
+  pclose(cmd_out);
+  return signature;
+}
+
+int AddKeySignature(FirmwareImage* image, char* root_key_file) {
+  int tmp_hdr_fd;
+  char* tmp_hdr_file = ".tmpHdrFile";
+  uint8_t* signature;
+
+  if(-1 == (tmp_hdr_fd = creat(tmp_hdr_file, S_IRWXU))) {
+    fprintf(stderr, "Could not open temporary file for writing "
+            "firmware header.\n");
+    return 0;
+  }
+  WriteFirmwareHeader(tmp_hdr_fd, image);
+  close(tmp_hdr_fd);
+
+  if (!(signature = SignatureFile(tmp_hdr_file, root_key_file,
+                                  ROOT_SIGNATURE_ALGORITHM)))
+    return 0;
+  Memcpy(image->key_signature, signature, RSA8192NUMBYTES);
+  return 1;
+}
+
+int AddFirmwareSignature(FirmwareImage* image, char* signing_key_file,
+                         int algorithm) {
+  int tmp_preamble_fd;
+  char* tmp_preamble_file = ".tmpPreambleFile";
+  int tmp_firmware_fd;
+  char* tmp_firmware_file = ".tmpFirmwareFile";
+  uint8_t* preamble_signature;
+  uint8_t* firmware_signature;
+  int signature_len = siglen_map[algorithm] * sizeof(uint32_t);
+
+  /* Write preamble to a file. */
+  if(-1 == (tmp_preamble_fd = creat(tmp_preamble_file, S_IRWXU))) {
+    fprintf(stderr, "Could not open temporary file for writing "
+            "firmware praemble.\n");
+    return 0;
+  }
+  WriteFirmwarePreamble(tmp_preamble_fd, image);
+  close(tmp_preamble_fd);
+  if (!(preamble_signature = SignatureFile(tmp_preamble_file, signing_key_file,
+                                           algorithm)))
+    return 0;
+  image->preamble_signature = (uint8_t*) Malloc(signature_len);
+  Memcpy(image->preamble_signature, preamble_signature, signature_len);
+  Free(preamble_signature);
+
+  if (-1 == (tmp_firmware_fd = creat(tmp_firmware_file, S_IRWXU))) {
+    fprintf(stderr, "Could not open temporary file for writing "
+            "firmware.\n");
+    return 0;
+  }
+  write(tmp_firmware_fd, image->firmware_data, image->firmware_len);
+  close(tmp_firmware_fd);
+
+  if (!(firmware_signature = SignatureFile(tmp_firmware_file, signing_key_file,
+                                           algorithm))) {
+    fprintf(stderr, "Could not open temporary file for writing "
+            "firmware.\n");
+    return 0;
+  }
+  image->firmware_signature = (uint8_t*) Malloc(signature_len);
+  Memcpy(image->firmware_signature, firmware_signature, signature_len);
+  Free(firmware_signature);
+  return 1;
+}
diff --git a/utils/firmware_utility.c b/utils/firmware_utility.c
new file mode 100644
index 0000000..1d94e21
--- /dev/null
+++ b/utils/firmware_utility.c
@@ -0,0 +1,23 @@
+/* Copyright (c) 2010 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.
+ *
+ * Utility for manipulating verified boot firmware images.
+ */
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "firmware_image.h"
+#include "rsa_utility.h"
+#include "sha_utility.h"
+#include "utility.h"
+
+int main(int argc, char* argv[]) {
+  /* TODO(gauravsh): TO BE IMPLEMENTED. */
+  return 0;
+}
diff --git a/utils/verify_data.c b/utils/verify_data.c
index 8f8b76b..5cb33f4 100644
--- a/utils/verify_data.c
+++ b/utils/verify_data.c
@@ -15,43 +15,13 @@
 #include <sys/types.h>
 #include <unistd.h>
 
+#include "file_keys.h"
 #include "sha_utility.h"
 #include "padding.h"
 #include "rsa.h"
 #include "rsa_utility.h"
 #include "verify_data.h"
 
-RSAPublicKey* read_RSAkey(char* input_file) {
-  int key_fd;
-  int buf_len;
-  struct stat stat_fd;
-  uint8_t* buf = NULL;
-
-  if ((key_fd = open(input_file, O_RDONLY)) == -1) {
-    fprintf(stderr, "Couldn't open pre-processed key file\n");
-    return NULL;
-  }
-
-  if (-1 == fstat(key_fd, &stat_fd)) {
-    fprintf(stderr, "Couldn't stat key file\n");
-    return NULL;
-  }
-  buf_len = stat_fd.st_size;
-
-  /* Read entire key binary blob into a buffer. */
-  buf = (uint8_t*) malloc(buf_len);
-  if (!buf)
-    return NULL;
-
-  if (buf_len != read(key_fd, buf, buf_len)) {
-    fprintf(stderr, "Couldn't read key into a buffer.\n");
-    return NULL;
-  }
-
-  close(key_fd);
-  return RSAPublicKeyFromBuf(buf, buf_len);
-}
-
 uint8_t* read_signature(char* input_file, int len) {
   int i, sigfd;
   uint8_t* signature = NULL;
@@ -102,7 +72,7 @@
   /* Length of the RSA Signature/RSA Key */
   sig_len = siglen_map[algorithm] * sizeof(uint32_t);
 
-  if (!(key = read_RSAkey(argv[2])))
+  if (!(key = RSAPublicKeyFromFile(argv[2])))
     goto failure;
   if (!(signature = read_signature(argv[3], sig_len)))
     goto failure;