AU: Payload Signer class

This class can take a private key and sign a blob of data. The API is
amenable to the upcoming change to delta_diff_generator that will use
it.

Also, minor change to the protobuf to support signatures.

TEST=unittests
BUG=5662

Review URL: http://codereview.chromium.org/3173032
diff --git a/SConstruct b/SConstruct
index 97444ef..b5c2c70 100644
--- a/SConstruct
+++ b/SConstruct
@@ -212,6 +212,7 @@
                    omaha_request_action.cc
                    omaha_request_params.cc
                    omaha_response_handler_action.cc
+                   payload_signer.cc
                    postinstall_runner_action.cc
                    prefs.cc
                    set_bootable_flag_action.cc
@@ -246,6 +247,7 @@
                             omaha_request_action_unittest.cc
                             omaha_request_params_unittest.cc
                             omaha_response_handler_action_unittest.cc
+                            payload_signer_unittest.cc
                             postinstall_runner_action_unittest.cc
                             prefs_unittest.cc
                             set_bootable_flag_action_unittest.cc
diff --git a/payload_signer.cc b/payload_signer.cc
new file mode 100644
index 0000000..03ff391
--- /dev/null
+++ b/payload_signer.cc
@@ -0,0 +1,79 @@
+// 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.
+
+#include "update_engine/payload_signer.h"
+
+#include "base/logging.h"
+#include "base/string_util.h"
+#include "update_engine/subprocess.h"
+#include "update_engine/update_metadata.pb.h"
+#include "update_engine/utils.h"
+
+using std::string;
+using std::vector;
+
+namespace chromeos_update_engine {
+
+const uint32_t kSignatureMessageVersion = 1;
+
+bool PayloadSigner::SignPayload(const string& unsigned_payload_path,
+                                const string& private_key_path,
+                                vector<char>* out_signature_blob) {
+  string sig_path;
+  TEST_AND_RETURN_FALSE(
+      utils::MakeTempFile("/tmp/signature.XXXXXX", &sig_path, NULL));
+  ScopedPathUnlinker sig_path_unlinker(sig_path);
+  
+  // This runs on the server, so it's okay to cop out and call openssl
+  // executable rather than properly use the library
+  vector<string> cmd;
+  SplitString("/usr/bin/openssl rsautl -pkcs -sign -inkey x -in x -out x",
+              ' ',
+              &cmd);
+  cmd[cmd.size() - 5] = private_key_path;
+  cmd[cmd.size() - 3] = unsigned_payload_path;
+  cmd[cmd.size() - 1] = sig_path;
+  
+  int return_code = 0;
+  TEST_AND_RETURN_FALSE(Subprocess::SynchronousExec(cmd, &return_code));
+  TEST_AND_RETURN_FALSE(return_code == 0);
+  
+  vector<char> signature;
+  TEST_AND_RETURN_FALSE(utils::ReadFile(sig_path, &signature));
+  
+  // Pack it into a protobuf
+  Signatures out_message;
+  Signatures_Signature* sig_message = out_message.add_signatures();
+  sig_message->set_version(kSignatureMessageVersion);
+  sig_message->set_data(signature.data(), signature.size());
+  
+  // Serialize protobuf
+  string serialized;
+  TEST_AND_RETURN_FALSE(out_message.AppendToString(&serialized));
+  out_signature_blob->insert(out_signature_blob->end(),
+                             serialized.begin(),
+                             serialized.end());
+  return true;
+}
+
+bool PayloadSigner::SignatureBlobLength(
+    const string& private_key_path,
+    uint64_t* out_length) {
+  DCHECK(out_length);
+  
+  string x_path;
+  TEST_AND_RETURN_FALSE(
+      utils::MakeTempFile("/tmp/signed_data.XXXXXX", &x_path, NULL));
+  ScopedPathUnlinker x_path_unlinker(x_path);
+  TEST_AND_RETURN_FALSE(utils::WriteFile(x_path.c_str(), "x", 1));
+
+  vector<char> sig_blob;
+  TEST_AND_RETURN_FALSE(PayloadSigner::SignPayload(x_path,
+                                                   private_key_path,
+                                                   &sig_blob));
+  *out_length = sig_blob.size();
+  return true;
+}
+
+}  // namespace chromeos_update_engine
diff --git a/payload_signer.h b/payload_signer.h
new file mode 100644
index 0000000..781a513
--- /dev/null
+++ b/payload_signer.h
@@ -0,0 +1,38 @@
+// 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.
+
+#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_PAYLOAD_SIGNER_H__
+#define CHROMEOS_PLATFORM_UPDATE_ENGINE_PAYLOAD_SIGNER_H__
+
+#include <string>
+#include <vector>
+#include "base/basictypes.h"
+
+// This function signs a payload with the OS vendor's private key.
+// It takes an update up to the signature blob and returns the signature
+// blob, which should be appended. See update_metadata.proto for more info.
+
+namespace chromeos_update_engine {
+
+extern const uint32_t kSignatureMessageVersion;
+
+class PayloadSigner {
+ public:
+  static bool SignPayload(const std::string& unsigned_payload_path,
+                          const std::string& private_key_path,
+                          std::vector<char>* out_signature_blob);
+
+  // Returns the length of out_signature_blob that will result in a call
+  // to SignPayload with a given private key. Returns true on success.
+  static bool SignatureBlobLength(const std::string& private_key_path,
+                                  uint64_t* out_length);
+
+ private:
+  // This should never be constructed
+  DISALLOW_IMPLICIT_CONSTRUCTORS(PayloadSigner);
+};
+
+}  // namespace chromeos_update_engine
+
+#endif  // CHROMEOS_PLATFORM_UPDATE_ENGINE_PAYLOAD_SIGNER_H__
diff --git a/payload_signer_unittest.cc b/payload_signer_unittest.cc
new file mode 100644
index 0000000..4388f3c
--- /dev/null
+++ b/payload_signer_unittest.cc
@@ -0,0 +1,79 @@
+// 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.
+
+#include <string>
+#include <vector>
+#include <gtest/gtest.h>
+#include "base/logging.h"
+#include "update_engine/payload_signer.h"
+#include "update_engine/update_metadata.pb.h"
+#include "update_engine/utils.h"
+
+using std::string;
+using std::vector;
+
+// Note: the test key was generated with the following command:
+// openssl genrsa -out unittest_key.pem 1024
+
+const char kUnittestPrivateKeyPath[] = "unittest_key.pem";
+
+namespace chromeos_update_engine {
+
+//class PayloadSignerTest : public ::testing::Test {};
+
+TEST(PayloadSignerTest, SimpleTest) {
+  // Some data and its corresponding signature:
+  const string kDataToSign = "This is some data to sign.";
+  const char kExpectedSignature[] = {
+    0x74, 0xd9, 0xea, 0x45, 0xf4, 0xd8, 0x64, 0x16,
+    0x88, 0x1b, 0x7f, 0x8b, 0x5d, 0xcb, 0x22, 0x2c,
+    0xb1, 0xce, 0x6d, 0x6d, 0x7c, 0x8f, 0x76, 0xf0,
+    0xb7, 0xa9, 0x80, 0xb3, 0x5e, 0x0b, 0xdd, 0x99,
+    0xfd, 0x88, 0x1f, 0x64, 0xd6, 0xac, 0x0c, 0x1b,
+    0xb1, 0x3c, 0x28, 0x11, 0x97, 0x15, 0x97, 0xec,
+    0x90, 0x25, 0xa0, 0x64, 0x90, 0x36, 0x5a, 0x96,
+    0x21, 0xdf, 0x16, 0x42, 0x6d, 0x7c, 0xb1, 0xf2,
+    0xf6, 0xe3, 0xb2, 0xa9, 0xea, 0xc8, 0xec, 0x6b,
+    0xa1, 0x99, 0x8a, 0xf0, 0x25, 0x0d, 0xcd, 0x41,
+    0x85, 0x76, 0x7c, 0xe1, 0xd6, 0x70, 0x71, 0xda,
+    0x02, 0x9f, 0xa2, 0x40, 0xb2, 0xfe, 0xfd, 0x84,
+    0x5c, 0xcf, 0x08, 0xa8, 0x50, 0x16, 0x46, 0xc1,
+    0x37, 0xe1, 0x16, 0xd2, 0xf5, 0x49, 0xe3, 0xcb,
+    0x58, 0x57, 0x11, 0x97, 0x49, 0x8f, 0x14, 0x1d,
+    0x4d, 0xa6, 0xfc, 0x75, 0x63, 0x64, 0xa3, 0xd5
+  };
+
+  string data_path;
+  ASSERT_TRUE(
+      utils::MakeTempFile("/tmp/data.XXXXXX", &data_path, NULL));
+  ScopedPathUnlinker data_path_unlinker(data_path);
+  ASSERT_TRUE(utils::WriteFile(data_path.c_str(),
+                               kDataToSign.data(),
+                               kDataToSign.size()));
+  uint64_t length = 0;
+  EXPECT_TRUE(PayloadSigner::SignatureBlobLength(kUnittestPrivateKeyPath,
+                                                 &length));
+  EXPECT_GT(length, 0);
+  vector<char> signature_blob;
+  EXPECT_TRUE(PayloadSigner::SignPayload(data_path,
+                                         kUnittestPrivateKeyPath,
+                                         &signature_blob));
+  EXPECT_EQ(length, signature_blob.size());
+
+  // Check the signature itself
+
+  Signatures signatures;
+  EXPECT_TRUE(signatures.ParseFromArray(&signature_blob[0],
+                                        signature_blob.size()));
+  EXPECT_EQ(1, signatures.signatures_size());
+  const Signatures_Signature& signature = signatures.signatures(0);
+  EXPECT_EQ(kSignatureMessageVersion, signature.version());
+  const string sig_data = signature.data();
+  ASSERT_EQ(sizeof(kExpectedSignature), sig_data.size());
+  for (size_t i = 0; i < sizeof(kExpectedSignature); i++) {
+    EXPECT_EQ(kExpectedSignature[i], sig_data[i]);
+  }
+}
+
+}  // namespace chromeos_update_engine
diff --git a/unittest_key.pem b/unittest_key.pem
new file mode 100644
index 0000000..f3867e4
--- /dev/null
+++ b/unittest_key.pem
@@ -0,0 +1,15 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIICXQIBAAKBgQDh27889vgney5Fmg89ZR80CFAhBWfj/33/6uRfWRs9tNP0kKpy
+Iml8Q4s6acPyp4VUlmfcayVKIkoNYhV+D9oRtNGmjosPCTRmupQ+55z0/FFHjtT5
+4sJShFvBcCofygvHeYqrzgpZdB8z1z/zhAfJc43hs2jFcr82UvkQ8XD3xwIDAQAB
+AoGAeiVwqFTcYeXBYYzu3wI4PNieFS2qQOjkyKnM9i/nhpir5GD0fSNVLwoMWvvm
+J+4nMlbhNpiPoycmK1S3UOTbxqFgw5b0DSUMiiGBdPIc7X0hPVIeR4I40g81fFl0
+3EyvZxlZexzfeTISbp+gpa+KW1bYoxY7e9TWCQDP+cuB34ECQQD5uJXzjU5AKTpA
+hgE1u2WetuGsnl95S96cBwuCiULAcbdFXQYip57eODfoNI2QDGyhdhcr3OBzhbR5
+ScK1qIXBAkEA54mPrA+65eEtv2fD4Iqt1qcvuVll/fSIdq6yQJEnzCUEsT7Ink0C
+WvAAHYlBISkc8onIagPowCQfGbVangQvhwJBAJ438HIOfpyyQmEtRkj4AausrZGE
+CnO8uT9cS1OaifuKURcWmFOOpl6fefSaj3LMHGu0eXvmByPKfA04ya/1JUECQQCX
+FQAW+jyue/zqBL+f6V39zyIpA9i1mbbiGqRd1Vnur8kcDyfBg+ahiDHLFCDXjohB
+Cv8njl114xwYHmp+6aRJAkAtumVpfP3KIAg7q7pXT5W1yTTqrzN/xAn4AQhnaXuh
+6Kt1dgWF7IQUEzoMKHBgciuwh2KjIxOx1/sMfLj3nz3H
+-----END RSA PRIVATE KEY-----
diff --git a/update_metadata.proto b/update_metadata.proto
index d849a8a..20c5d9f 100644
--- a/update_metadata.proto
+++ b/update_metadata.proto
@@ -7,7 +7,7 @@
 // version. The update format is represented by this struct pseudocode:
 // struct delta_update_file {
 //   char magic[4] = "CrAU";
-//   uint32 file_format_version = 1;
+//   uint64 file_format_version = 1;
 //   uint64 manifest_size;  // Size of protobuf DeltaArchiveManifest
 //   // The Bzip2 compressed DeltaArchiveManifest
 //   char manifest[];
@@ -80,7 +80,7 @@
 message Signatures {
   message Signature {
     optional uint32 version = 1;
-    optional string data = 2;
+    optional bytes data = 2;
   }
   repeated Signature signatures = 1;
 }