1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/component_updater/component_unpacker.h"
10 #include "base/bind.h"
11 #include "base/file_util.h"
12 #include "base/files/file_path.h"
13 #include "base/files/scoped_file.h"
14 #include "base/json/json_file_value_serializer.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/values.h"
20 #include "chrome/browser/component_updater/component_patcher.h"
21 #include "chrome/browser/component_updater/component_patcher_operation.h"
22 #include "chrome/browser/component_updater/component_updater_service.h"
23 #include "components/crx_file/constants.h"
24 #include "components/crx_file/crx_file.h"
25 #include "crypto/secure_hash.h"
26 #include "crypto/signature_verifier.h"
27 #include "third_party/zlib/google/zip.h"
29 using crypto::SecureHash;
31 namespace component_updater {
35 // This class makes sure that the CRX digital signature is valid
39 explicit CRXValidator(FILE* crx_file) : valid_(false), is_delta_(false) {
40 crx_file::CrxFile::Header header;
41 size_t len = fread(&header, 1, sizeof(header), crx_file);
42 if (len < sizeof(header))
45 crx_file::CrxFile::Error error;
46 scoped_ptr<crx_file::CrxFile> crx(
47 crx_file::CrxFile::Parse(header, &error));
50 is_delta_ = crx_file::CrxFile::HeaderIsDelta(header);
52 std::vector<uint8> key(header.key_size);
53 len = fread(&key[0], sizeof(uint8), header.key_size, crx_file);
54 if (len < header.key_size)
57 std::vector<uint8> signature(header.signature_size);
58 len = fread(&signature[0], sizeof(uint8), header.signature_size, crx_file);
59 if (len < header.signature_size)
62 crypto::SignatureVerifier verifier;
63 if (!verifier.VerifyInit(crx_file::kSignatureAlgorithm,
64 sizeof(crx_file::kSignatureAlgorithm),
69 // Signature verification initialization failed. This is most likely
70 // caused by a public key in the wrong format (should encode algorithm).
74 const size_t kBufSize = 8 * 1024;
75 scoped_ptr<uint8[]> buf(new uint8[kBufSize]);
76 while ((len = fread(buf.get(), 1, kBufSize, crx_file)) > 0)
77 verifier.VerifyUpdate(buf.get(), len);
79 if (!verifier.VerifyFinal())
82 public_key_.swap(key);
86 bool valid() const { return valid_; }
88 bool is_delta() const { return is_delta_; }
90 const std::vector<uint8>& public_key() const { return public_key_; }
95 std::vector<uint8> public_key_;
100 ComponentUnpacker::ComponentUnpacker(
101 const std::vector<uint8>& pk_hash,
102 const base::FilePath& path,
103 const std::string& fingerprint,
104 ComponentInstaller* installer,
105 scoped_refptr<OutOfProcessPatcher> out_of_process_patcher,
106 scoped_refptr<base::SequencedTaskRunner> task_runner)
110 fingerprint_(fingerprint),
111 installer_(installer),
112 out_of_process_patcher_(out_of_process_patcher),
115 task_runner_(task_runner) {
118 // TODO(cpu): add a specific attribute check to a component json that the
119 // extension unpacker will reject, so that a component cannot be installed
121 scoped_ptr<base::DictionaryValue> ReadManifest(
122 const base::FilePath& unpack_path) {
123 base::FilePath manifest =
124 unpack_path.Append(FILE_PATH_LITERAL("manifest.json"));
125 if (!base::PathExists(manifest))
126 return scoped_ptr<base::DictionaryValue>();
127 JSONFileValueSerializer serializer(manifest);
129 scoped_ptr<base::Value> root(serializer.Deserialize(NULL, &error));
131 return scoped_ptr<base::DictionaryValue>();
132 if (!root->IsType(base::Value::TYPE_DICTIONARY))
133 return scoped_ptr<base::DictionaryValue>();
134 return scoped_ptr<base::DictionaryValue>(
135 static_cast<base::DictionaryValue*>(root.release())).Pass();
138 bool ComponentUnpacker::UnpackInternal() {
139 return Verify() && Unzip() && BeginPatching();
142 void ComponentUnpacker::Unpack(const Callback& callback) {
143 callback_ = callback;
144 if (!UnpackInternal())
148 bool ComponentUnpacker::Verify() {
149 VLOG(1) << "Verifying component: " << path_.value();
150 if (pk_hash_.empty() || path_.empty()) {
151 error_ = kInvalidParams;
154 // First, validate the CRX header and signature. As of today
155 // this is SHA1 with RSA 1024.
156 base::ScopedFILE file(base::OpenFile(path_, "rb"));
158 error_ = kInvalidFile;
161 CRXValidator validator(file.get());
163 if (!validator.valid()) {
164 error_ = kInvalidFile;
167 is_delta_ = validator.is_delta();
169 // File is valid and the digital signature matches. Now make sure
170 // the public key hash matches the expected hash. If they do we fully
173 scoped_ptr<SecureHash> sha256(SecureHash::Create(SecureHash::SHA256));
174 sha256->Update(&(validator.public_key()[0]), validator.public_key().size());
175 sha256->Finish(hash, arraysize(hash));
177 if (!std::equal(pk_hash_.begin(), pk_hash_.end(), hash)) {
178 VLOG(1) << "Hash mismatch: " << path_.value();
182 VLOG(1) << "Verification successful: " << path_.value();
186 bool ComponentUnpacker::Unzip() {
187 base::FilePath& destination = is_delta_ ? unpack_diff_path_ : unpack_path_;
188 VLOG(1) << "Unpacking in: " << destination.value();
189 if (!base::CreateNewTempDirectory(base::FilePath::StringType(),
191 VLOG(1) << "Unable to create temporary directory for unpacking.";
192 error_ = kUnzipPathError;
195 if (!zip::Unzip(path_, destination)) {
196 VLOG(1) << "Unzipping failed.";
197 error_ = kUnzipFailed;
200 VLOG(1) << "Unpacked successfully";
204 bool ComponentUnpacker::BeginPatching() {
205 if (is_delta_) { // Package is a diff package.
206 // Use a different temp directory for the patch output files.
207 if (!base::CreateNewTempDirectory(base::FilePath::StringType(),
209 error_ = kUnzipPathError;
212 patcher_ = new ComponentPatcher(unpack_diff_path_,
215 out_of_process_patcher_,
217 task_runner_->PostTask(
219 base::Bind(&ComponentPatcher::Start,
221 base::Bind(&ComponentUnpacker::EndPatching,
222 scoped_refptr<ComponentUnpacker>(this))));
224 task_runner_->PostTask(FROM_HERE,
225 base::Bind(&ComponentUnpacker::EndPatching,
226 scoped_refptr<ComponentUnpacker>(this),
233 void ComponentUnpacker::EndPatching(Error error, int extended_error) {
235 extended_error_ = extended_error;
237 if (error_ != kNone) {
241 // Optimization: clean up patch files early, in case disk space is too low to
242 // install otherwise.
243 if (!unpack_diff_path_.empty()) {
244 base::DeleteFile(unpack_diff_path_, true);
245 unpack_diff_path_.clear();
251 void ComponentUnpacker::Install() {
252 // Write the fingerprint to disk.
253 if (static_cast<int>(fingerprint_.size()) !=
255 unpack_path_.Append(FILE_PATH_LITERAL("manifest.fingerprint")),
256 fingerprint_.c_str(),
257 fingerprint_.size())) {
258 error_ = kFingerprintWriteFailed;
261 scoped_ptr<base::DictionaryValue> manifest(ReadManifest(unpack_path_));
262 if (!manifest.get()) {
263 error_ = kBadManifest;
266 DCHECK(error_ == kNone);
267 if (!installer_->Install(*manifest, unpack_path_)) {
268 error_ = kInstallerError;
273 void ComponentUnpacker::Finish() {
274 if (!unpack_diff_path_.empty())
275 base::DeleteFile(unpack_diff_path_, true);
276 if (!unpack_path_.empty())
277 base::DeleteFile(unpack_path_, true);
278 callback_.Run(error_, extended_error_);
281 ComponentUnpacker::~ComponentUnpacker() {
284 } // namespace component_updater