ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / extensions / browser / sandboxed_unpacker.cc
blob518cde7c0808b74d8079f1174837f41c67973abd
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 "extensions/browser/sandboxed_unpacker.h"
7 #include <set>
9 #include "base/base64.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/files/file_util_proxy.h"
14 #include "base/files/scoped_file.h"
15 #include "base/json/json_string_value_serializer.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/numerics/safe_conversions.h"
19 #include "base/path_service.h"
20 #include "base/sequenced_task_runner.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/threading/sequenced_worker_pool.h"
24 #include "components/crx_file/constants.h"
25 #include "components/crx_file/crx_file.h"
26 #include "components/crx_file/id_util.h"
27 #include "content/public/browser/browser_thread.h"
28 #include "content/public/browser/utility_process_host.h"
29 #include "content/public/common/common_param_traits.h"
30 #include "crypto/secure_hash.h"
31 #include "crypto/sha2.h"
32 #include "crypto/signature_verifier.h"
33 #include "extensions/common/constants.h"
34 #include "extensions/common/extension.h"
35 #include "extensions/common/extension_l10n_util.h"
36 #include "extensions/common/extension_utility_messages.h"
37 #include "extensions/common/extensions_client.h"
38 #include "extensions/common/file_util.h"
39 #include "extensions/common/manifest_constants.h"
40 #include "extensions/common/manifest_handlers/icons_handler.h"
41 #include "extensions/common/switches.h"
42 #include "grit/extensions_strings.h"
43 #include "third_party/skia/include/core/SkBitmap.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/gfx/codec/png_codec.h"
47 using base::ASCIIToUTF16;
48 using content::BrowserThread;
49 using content::UtilityProcessHost;
50 using crx_file::CrxFile;
52 // The following macro makes histograms that record the length of paths
53 // in this file much easier to read.
54 // Windows has a short max path length. If the path length to a
55 // file being unpacked from a CRX exceeds the max length, we might
56 // fail to install. To see if this is happening, see how long the
57 // path to the temp unpack directory is. See crbug.com/69693 .
58 #define PATH_LENGTH_HISTOGRAM(name, path) \
59 UMA_HISTOGRAM_CUSTOM_COUNTS(name, path.value().length(), 0, 500, 100)
61 // Record a rate (kB per second) at which extensions are unpacked.
62 // Range from 1kB/s to 100mB/s.
63 #define UNPACK_RATE_HISTOGRAM(name, rate) \
64 UMA_HISTOGRAM_CUSTOM_COUNTS(name, rate, 1, 100000, 100);
66 namespace extensions {
67 namespace {
69 void RecordSuccessfulUnpackTimeHistograms(const base::FilePath& crx_path,
70 const base::TimeDelta unpack_time) {
71 const int64 kBytesPerKb = 1024;
72 const int64 kBytesPerMb = 1024 * 1024;
74 UMA_HISTOGRAM_TIMES("Extensions.SandboxUnpackSuccessTime", unpack_time);
76 // To get a sense of how CRX size impacts unpack time, record unpack
77 // time for several increments of CRX size.
78 int64 crx_file_size;
79 if (!base::GetFileSize(crx_path, &crx_file_size)) {
80 UMA_HISTOGRAM_COUNTS("Extensions.SandboxUnpackSuccessCantGetCrxSize", 1);
81 return;
84 // Cast is safe as long as the number of bytes in the CRX is less than
85 // 2^31 * 2^10.
86 int crx_file_size_kb = static_cast<int>(crx_file_size / kBytesPerKb);
87 UMA_HISTOGRAM_COUNTS("Extensions.SandboxUnpackSuccessCrxSize",
88 crx_file_size_kb);
90 // We have time in seconds and file size in bytes. We want the rate bytes are
91 // unpacked in kB/s.
92 double file_size_kb =
93 static_cast<double>(crx_file_size) / static_cast<double>(kBytesPerKb);
94 int unpack_rate_kb_per_s =
95 static_cast<int>(file_size_kb / unpack_time.InSecondsF());
96 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate", unpack_rate_kb_per_s);
98 if (crx_file_size < 50.0 * kBytesPerKb) {
99 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRateUnder50kB",
100 unpack_rate_kb_per_s);
102 } else if (crx_file_size < 1 * kBytesPerMb) {
103 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate50kBTo1mB",
104 unpack_rate_kb_per_s);
106 } else if (crx_file_size < 2 * kBytesPerMb) {
107 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate1To2mB",
108 unpack_rate_kb_per_s);
110 } else if (crx_file_size < 5 * kBytesPerMb) {
111 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate2To5mB",
112 unpack_rate_kb_per_s);
114 } else if (crx_file_size < 10 * kBytesPerMb) {
115 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRate5To10mB",
116 unpack_rate_kb_per_s);
118 } else {
119 UNPACK_RATE_HISTOGRAM("Extensions.SandboxUnpackRateOver10mB",
120 unpack_rate_kb_per_s);
124 // Work horse for FindWritableTempLocation. Creates a temp file in the folder
125 // and uses NormalizeFilePath to check if the path is junction free.
126 bool VerifyJunctionFreeLocation(base::FilePath* temp_dir) {
127 if (temp_dir->empty())
128 return false;
130 base::FilePath temp_file;
131 if (!base::CreateTemporaryFileInDir(*temp_dir, &temp_file)) {
132 LOG(ERROR) << temp_dir->value() << " is not writable";
133 return false;
135 // NormalizeFilePath requires a non-empty file, so write some data.
136 // If you change the exit points of this function please make sure all
137 // exit points delete this temp file!
138 if (base::WriteFile(temp_file, ".", 1) != 1)
139 return false;
141 base::FilePath normalized_temp_file;
142 bool normalized = base::NormalizeFilePath(temp_file, &normalized_temp_file);
143 if (!normalized) {
144 // If |temp_file| contains a link, the sandbox will block al file system
145 // operations, and the install will fail.
146 LOG(ERROR) << temp_dir->value() << " seem to be on remote drive.";
147 } else {
148 *temp_dir = normalized_temp_file.DirName();
150 // Clean up the temp file.
151 base::DeleteFile(temp_file, false);
153 return normalized;
156 // This function tries to find a location for unpacking the extension archive
157 // that is writable and does not lie on a shared drive so that the sandboxed
158 // unpacking process can write there. If no such location exists we can not
159 // proceed and should fail.
160 // The result will be written to |temp_dir|. The function will write to this
161 // parameter even if it returns false.
162 bool FindWritableTempLocation(const base::FilePath& extensions_dir,
163 base::FilePath* temp_dir) {
164 // On ChromeOS, we will only attempt to unpack extension in cryptohome (profile)
165 // directory to provide additional security/privacy and speed up the rest of
166 // the extension install process.
167 #if !defined(OS_CHROMEOS)
168 PathService::Get(base::DIR_TEMP, temp_dir);
169 if (VerifyJunctionFreeLocation(temp_dir))
170 return true;
171 #endif
173 *temp_dir = file_util::GetInstallTempDir(extensions_dir);
174 if (VerifyJunctionFreeLocation(temp_dir))
175 return true;
176 // Neither paths is link free chances are good installation will fail.
177 LOG(ERROR) << "Both the %TEMP% folder and the profile seem to be on "
178 << "remote drives or read-only. Installation can not complete!";
179 return false;
182 // Read the decoded images back from the file we saved them to.
183 // |extension_path| is the path to the extension we unpacked that wrote the
184 // data. Returns true on success.
185 bool ReadImagesFromFile(const base::FilePath& extension_path,
186 DecodedImages* images) {
187 base::FilePath path = extension_path.AppendASCII(kDecodedImagesFilename);
188 std::string file_str;
189 if (!base::ReadFileToString(path, &file_str))
190 return false;
192 IPC::Message pickle(file_str.data(), file_str.size());
193 PickleIterator iter(pickle);
194 return IPC::ReadParam(&pickle, &iter, images);
197 // Read the decoded message catalogs back from the file we saved them to.
198 // |extension_path| is the path to the extension we unpacked that wrote the
199 // data. Returns true on success.
200 bool ReadMessageCatalogsFromFile(const base::FilePath& extension_path,
201 base::DictionaryValue* catalogs) {
202 base::FilePath path =
203 extension_path.AppendASCII(kDecodedMessageCatalogsFilename);
204 std::string file_str;
205 if (!base::ReadFileToString(path, &file_str))
206 return false;
208 IPC::Message pickle(file_str.data(), file_str.size());
209 PickleIterator iter(pickle);
210 return IPC::ReadParam(&pickle, &iter, catalogs);
213 } // namespace
215 SandboxedUnpacker::SandboxedUnpacker(
216 const CRXFileInfo& file,
217 Manifest::Location location,
218 int creation_flags,
219 const base::FilePath& extensions_dir,
220 const scoped_refptr<base::SequencedTaskRunner>& unpacker_io_task_runner,
221 SandboxedUnpackerClient* client)
222 : crx_path_(file.path),
223 package_hash_(base::StringToLowerASCII(file.expected_hash)),
224 check_crx_hash_(false),
225 client_(client),
226 extensions_dir_(extensions_dir),
227 got_response_(false),
228 location_(location),
229 creation_flags_(creation_flags),
230 unpacker_io_task_runner_(unpacker_io_task_runner) {
231 if (!package_hash_.empty()) {
232 check_crx_hash_ = base::CommandLine::ForCurrentProcess()->HasSwitch(
233 extensions::switches::kEnableCrxHashCheck);
237 bool SandboxedUnpacker::CreateTempDirectory() {
238 CHECK(unpacker_io_task_runner_->RunsTasksOnCurrentThread());
240 base::FilePath temp_dir;
241 if (!FindWritableTempLocation(extensions_dir_, &temp_dir)) {
242 ReportFailure(COULD_NOT_GET_TEMP_DIRECTORY,
243 l10n_util::GetStringFUTF16(
244 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
245 ASCIIToUTF16("COULD_NOT_GET_TEMP_DIRECTORY")));
246 return false;
249 if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_dir)) {
250 ReportFailure(COULD_NOT_CREATE_TEMP_DIRECTORY,
251 l10n_util::GetStringFUTF16(
252 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
253 ASCIIToUTF16("COULD_NOT_CREATE_TEMP_DIRECTORY")));
254 return false;
257 return true;
260 void SandboxedUnpacker::Start() {
261 // We assume that we are started on the thread that the client wants us to do
262 // file IO on.
263 CHECK(unpacker_io_task_runner_->RunsTasksOnCurrentThread());
265 unpack_start_time_ = base::TimeTicks::Now();
267 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackInitialCrxPathLength",
268 crx_path_);
269 if (!CreateTempDirectory())
270 return; // ReportFailure() already called.
272 // Initialize the path that will eventually contain the unpacked extension.
273 extension_root_ = temp_dir_.path().AppendASCII(kTempExtensionName);
274 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackUnpackedCrxPathLength",
275 extension_root_);
277 // Extract the public key and validate the package.
278 if (!ValidateSignature())
279 return; // ValidateSignature() already reported the error.
281 // Copy the crx file into our working directory.
282 base::FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName());
283 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackTempCrxPathLength",
284 temp_crx_path);
286 if (!base::CopyFile(crx_path_, temp_crx_path)) {
287 // Failed to copy extension file to temporary directory.
288 ReportFailure(
289 FAILED_TO_COPY_EXTENSION_FILE_TO_TEMP_DIRECTORY,
290 l10n_util::GetStringFUTF16(
291 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
292 ASCIIToUTF16("FAILED_TO_COPY_EXTENSION_FILE_TO_TEMP_DIRECTORY")));
293 return;
296 // The utility process will have access to the directory passed to
297 // SandboxedUnpacker. That directory should not contain a symlink or NTFS
298 // reparse point. When the path is used, following the link/reparse point
299 // will cause file system access outside the sandbox path, and the sandbox
300 // will deny the operation.
301 base::FilePath link_free_crx_path;
302 if (!base::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) {
303 LOG(ERROR) << "Could not get the normalized path of "
304 << temp_crx_path.value();
305 ReportFailure(COULD_NOT_GET_SANDBOX_FRIENDLY_PATH,
306 l10n_util::GetStringUTF16(IDS_EXTENSION_UNPACK_FAILED));
307 return;
309 PATH_LENGTH_HISTOGRAM("Extensions.SandboxUnpackLinkFreeCrxPathLength",
310 link_free_crx_path);
312 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
313 base::Bind(&SandboxedUnpacker::StartProcessOnIOThread,
314 this, link_free_crx_path));
317 SandboxedUnpacker::~SandboxedUnpacker() {
320 bool SandboxedUnpacker::OnMessageReceived(const IPC::Message& message) {
321 bool handled = true;
322 IPC_BEGIN_MESSAGE_MAP(SandboxedUnpacker, message)
323 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_UnpackExtension_Succeeded,
324 OnUnpackExtensionSucceeded)
325 IPC_MESSAGE_HANDLER(ChromeUtilityHostMsg_UnpackExtension_Failed,
326 OnUnpackExtensionFailed)
327 IPC_MESSAGE_UNHANDLED(handled = false)
328 IPC_END_MESSAGE_MAP()
329 return handled;
332 void SandboxedUnpacker::OnProcessCrashed(int exit_code) {
333 // Don't report crashes if they happen after we got a response.
334 if (got_response_)
335 return;
337 // Utility process crashed while trying to install.
338 ReportFailure(
339 UTILITY_PROCESS_CRASHED_WHILE_TRYING_TO_INSTALL,
340 l10n_util::GetStringFUTF16(
341 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
342 ASCIIToUTF16("UTILITY_PROCESS_CRASHED_WHILE_TRYING_TO_INSTALL")) +
343 ASCIIToUTF16(". ") +
344 l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_PROCESS_CRASHED));
347 void SandboxedUnpacker::StartProcessOnIOThread(
348 const base::FilePath& temp_crx_path) {
349 UtilityProcessHost* host =
350 UtilityProcessHost::Create(this, unpacker_io_task_runner_.get());
351 // Grant the subprocess access to the entire subdir the extension file is
352 // in, so that it can unpack to that dir.
353 host->SetExposedDir(temp_crx_path.DirName());
354 host->Send(new ChromeUtilityMsg_UnpackExtension(temp_crx_path, extension_id_,
355 location_, creation_flags_));
358 void SandboxedUnpacker::OnUnpackExtensionSucceeded(
359 const base::DictionaryValue& manifest) {
360 CHECK(unpacker_io_task_runner_->RunsTasksOnCurrentThread());
361 got_response_ = true;
363 scoped_ptr<base::DictionaryValue> final_manifest(
364 RewriteManifestFile(manifest));
365 if (!final_manifest)
366 return;
368 // Create an extension object that refers to the temporary location the
369 // extension was unpacked to. We use this until the extension is finally
370 // installed. For example, the install UI shows images from inside the
371 // extension.
373 // Localize manifest now, so confirm UI gets correct extension name.
375 // TODO(rdevlin.cronin): Continue removing std::string errors and replacing
376 // with base::string16
377 std::string utf8_error;
378 if (!extension_l10n_util::LocalizeExtension(
379 extension_root_, final_manifest.get(), &utf8_error)) {
380 ReportFailure(
381 COULD_NOT_LOCALIZE_EXTENSION,
382 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_MESSAGE,
383 base::UTF8ToUTF16(utf8_error)));
384 return;
387 extension_ =
388 Extension::Create(extension_root_, location_, *final_manifest,
389 Extension::REQUIRE_KEY | creation_flags_, &utf8_error);
391 if (!extension_.get()) {
392 ReportFailure(INVALID_MANIFEST,
393 ASCIIToUTF16("Manifest is invalid: " + utf8_error));
394 return;
397 SkBitmap install_icon;
398 if (!RewriteImageFiles(&install_icon))
399 return;
401 if (!RewriteCatalogFiles())
402 return;
404 ReportSuccess(manifest, install_icon);
407 void SandboxedUnpacker::OnUnpackExtensionFailed(const base::string16& error) {
408 CHECK(unpacker_io_task_runner_->RunsTasksOnCurrentThread());
409 got_response_ = true;
410 ReportFailure(
411 UNPACKER_CLIENT_FAILED,
412 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_MESSAGE, error));
415 static size_t ReadAndHash(void* ptr,
416 size_t size,
417 size_t nmemb,
418 FILE* stream,
419 scoped_ptr<crypto::SecureHash>& hash) {
420 size_t len = fread(ptr, size, nmemb, stream);
421 if (len > 0 && hash) {
422 hash->Update(ptr, len * size);
424 return len;
427 bool SandboxedUnpacker::FinalizeHash(scoped_ptr<crypto::SecureHash>& hash) {
428 if (hash) {
429 uint8 output[crypto::kSHA256Length];
430 hash->Finish(output, sizeof(output));
431 std::string real_hash =
432 base::StringToLowerASCII(base::HexEncode(output, sizeof(output)));
433 bool result = (real_hash == package_hash_);
434 UMA_HISTOGRAM_BOOLEAN("Extensions.SandboxUnpackHashCheck", result);
435 if (!result && check_crx_hash_) {
436 // Package hash verification failed
437 LOG(ERROR) << "Hash check failed for extension: " << extension_id_
438 << ", expected " << package_hash_ << ", got " << real_hash;
439 ReportFailure(CRX_HASH_VERIFICATION_FAILED,
440 l10n_util::GetStringFUTF16(
441 IDS_EXTENSION_PACKAGE_ERROR_CODE,
442 ASCIIToUTF16("CRX_HASH_VERIFICATION_FAILED")));
443 return false;
447 return true;
450 bool SandboxedUnpacker::ValidateSignature() {
451 base::ScopedFILE file(base::OpenFile(crx_path_, "rb"));
453 scoped_ptr<crypto::SecureHash> hash;
455 if (!package_hash_.empty()) {
456 hash.reset(crypto::SecureHash::Create(crypto::SecureHash::SHA256));
459 if (!file.get()) {
460 // Could not open crx file for reading.
461 #if defined(OS_WIN)
462 // On windows, get the error code.
463 uint32 error_code = ::GetLastError();
464 // TODO(skerner): Use this histogram to understand why so many
465 // windows users hit this error. crbug.com/69693
467 // Windows errors are unit32s, but all of likely errors are in
468 // [1, 1000]. See winerror.h for the meaning of specific values.
469 // Clip errors outside the expected range to a single extra value.
470 // If there are errors in that extra bucket, we will know to expand
471 // the range.
472 const uint32 kMaxErrorToSend = 1001;
473 error_code = std::min(error_code, kMaxErrorToSend);
474 UMA_HISTOGRAM_ENUMERATION("Extensions.ErrorCodeFromCrxOpen", error_code,
475 kMaxErrorToSend);
476 #endif
478 ReportFailure(
479 CRX_FILE_NOT_READABLE,
480 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE,
481 ASCIIToUTF16("CRX_FILE_NOT_READABLE")));
482 return false;
485 // Read and verify the header.
486 // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it
487 // appears that we don't have any endian/alignment aware serialization
488 // code in the code base. So for now, this assumes that we're running
489 // on a little endian machine with 4 byte alignment.
490 CrxFile::Header header;
491 size_t len = ReadAndHash(&header, 1, sizeof(header), file.get(), hash);
492 if (len < sizeof(header)) {
493 // Invalid crx header
494 ReportFailure(CRX_HEADER_INVALID, l10n_util::GetStringFUTF16(
495 IDS_EXTENSION_PACKAGE_ERROR_CODE,
496 ASCIIToUTF16("CRX_HEADER_INVALID")));
497 return false;
500 CrxFile::Error error;
501 scoped_ptr<CrxFile> crx(CrxFile::Parse(header, &error));
502 if (!crx) {
503 switch (error) {
504 case CrxFile::kWrongMagic:
505 ReportFailure(CRX_MAGIC_NUMBER_INVALID,
506 l10n_util::GetStringFUTF16(
507 IDS_EXTENSION_PACKAGE_ERROR_CODE,
508 ASCIIToUTF16("CRX_MAGIC_NUMBER_INVALID")));
509 break;
510 case CrxFile::kInvalidVersion:
511 // Bad version numer
512 ReportFailure(CRX_VERSION_NUMBER_INVALID,
513 l10n_util::GetStringFUTF16(
514 IDS_EXTENSION_PACKAGE_ERROR_CODE,
515 ASCIIToUTF16("CRX_VERSION_NUMBER_INVALID")));
516 break;
517 case CrxFile::kInvalidKeyTooLarge:
518 case CrxFile::kInvalidSignatureTooLarge:
519 // Excessively large key or signature
520 ReportFailure(
521 CRX_EXCESSIVELY_LARGE_KEY_OR_SIGNATURE,
522 l10n_util::GetStringFUTF16(
523 IDS_EXTENSION_PACKAGE_ERROR_CODE,
524 ASCIIToUTF16("CRX_EXCESSIVELY_LARGE_KEY_OR_SIGNATURE")));
525 break;
526 case CrxFile::kInvalidKeyTooSmall:
527 // Key length is zero
528 ReportFailure(
529 CRX_ZERO_KEY_LENGTH,
530 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE,
531 ASCIIToUTF16("CRX_ZERO_KEY_LENGTH")));
532 break;
533 case CrxFile::kInvalidSignatureTooSmall:
534 // Signature length is zero
535 ReportFailure(CRX_ZERO_SIGNATURE_LENGTH,
536 l10n_util::GetStringFUTF16(
537 IDS_EXTENSION_PACKAGE_ERROR_CODE,
538 ASCIIToUTF16("CRX_ZERO_SIGNATURE_LENGTH")));
539 break;
541 return false;
544 std::vector<uint8> key;
545 key.resize(header.key_size);
546 len = ReadAndHash(&key.front(), sizeof(uint8), header.key_size, file.get(),
547 hash);
548 if (len < header.key_size) {
549 // Invalid public key
550 ReportFailure(
551 CRX_PUBLIC_KEY_INVALID,
552 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE,
553 ASCIIToUTF16("CRX_PUBLIC_KEY_INVALID")));
554 return false;
557 std::vector<uint8> signature;
558 signature.resize(header.signature_size);
559 len = ReadAndHash(&signature.front(), sizeof(uint8), header.signature_size,
560 file.get(), hash);
561 if (len < header.signature_size) {
562 // Invalid signature
563 ReportFailure(
564 CRX_SIGNATURE_INVALID,
565 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_ERROR_CODE,
566 ASCIIToUTF16("CRX_SIGNATURE_INVALID")));
567 return false;
570 crypto::SignatureVerifier verifier;
571 if (!verifier.VerifyInit(
572 crx_file::kSignatureAlgorithm, sizeof(crx_file::kSignatureAlgorithm),
573 &signature.front(), signature.size(), &key.front(), key.size())) {
574 // Signature verification initialization failed. This is most likely
575 // caused by a public key in the wrong format (should encode algorithm).
576 ReportFailure(
577 CRX_SIGNATURE_VERIFICATION_INITIALIZATION_FAILED,
578 l10n_util::GetStringFUTF16(
579 IDS_EXTENSION_PACKAGE_ERROR_CODE,
580 ASCIIToUTF16("CRX_SIGNATURE_VERIFICATION_INITIALIZATION_FAILED")));
581 return false;
584 unsigned char buf[1 << 12];
585 while ((len = ReadAndHash(buf, 1, sizeof(buf), file.get(), hash)) > 0)
586 verifier.VerifyUpdate(buf, len);
588 if (!verifier.VerifyFinal()) {
589 // Signature verification failed
590 ReportFailure(CRX_SIGNATURE_VERIFICATION_FAILED,
591 l10n_util::GetStringFUTF16(
592 IDS_EXTENSION_PACKAGE_ERROR_CODE,
593 ASCIIToUTF16("CRX_SIGNATURE_VERIFICATION_FAILED")));
594 return false;
597 std::string public_key =
598 std::string(reinterpret_cast<char*>(&key.front()), key.size());
599 base::Base64Encode(public_key, &public_key_);
601 extension_id_ = crx_file::id_util::GenerateId(public_key);
603 return FinalizeHash(hash);
606 void SandboxedUnpacker::ReportFailure(FailureReason reason,
607 const base::string16& error) {
608 UMA_HISTOGRAM_ENUMERATION("Extensions.SandboxUnpackFailureReason", reason,
609 NUM_FAILURE_REASONS);
610 UMA_HISTOGRAM_TIMES("Extensions.SandboxUnpackFailureTime",
611 base::TimeTicks::Now() - unpack_start_time_);
612 Cleanup();
614 CrxInstallError error_info(reason == CRX_HASH_VERIFICATION_FAILED
615 ? CrxInstallError::ERROR_HASH_MISMATCH
616 : CrxInstallError::ERROR_OTHER,
617 error);
619 client_->OnUnpackFailure(error_info);
622 void SandboxedUnpacker::ReportSuccess(
623 const base::DictionaryValue& original_manifest,
624 const SkBitmap& install_icon) {
625 UMA_HISTOGRAM_COUNTS("Extensions.SandboxUnpackSuccess", 1);
627 RecordSuccessfulUnpackTimeHistograms(
628 crx_path_, base::TimeTicks::Now() - unpack_start_time_);
630 // Client takes ownership of temporary directory and extension.
631 client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_,
632 &original_manifest, extension_.get(), install_icon);
633 extension_ = NULL;
636 base::DictionaryValue* SandboxedUnpacker::RewriteManifestFile(
637 const base::DictionaryValue& manifest) {
638 // Add the public key extracted earlier to the parsed manifest and overwrite
639 // the original manifest. We do this to ensure the manifest doesn't contain an
640 // exploitable bug that could be used to compromise the browser.
641 scoped_ptr<base::DictionaryValue> final_manifest(manifest.DeepCopy());
642 final_manifest->SetString(manifest_keys::kPublicKey, public_key_);
644 std::string manifest_json;
645 JSONStringValueSerializer serializer(&manifest_json);
646 serializer.set_pretty_print(true);
647 if (!serializer.Serialize(*final_manifest)) {
648 // Error serializing manifest.json.
649 ReportFailure(ERROR_SERIALIZING_MANIFEST_JSON,
650 l10n_util::GetStringFUTF16(
651 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
652 ASCIIToUTF16("ERROR_SERIALIZING_MANIFEST_JSON")));
653 return NULL;
656 base::FilePath manifest_path = extension_root_.Append(kManifestFilename);
657 int size = base::checked_cast<int>(manifest_json.size());
658 if (base::WriteFile(manifest_path, manifest_json.data(), size) != size) {
659 // Error saving manifest.json.
660 ReportFailure(
661 ERROR_SAVING_MANIFEST_JSON,
662 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
663 ASCIIToUTF16("ERROR_SAVING_MANIFEST_JSON")));
664 return NULL;
667 return final_manifest.release();
670 bool SandboxedUnpacker::RewriteImageFiles(SkBitmap* install_icon) {
671 DecodedImages images;
672 if (!ReadImagesFromFile(temp_dir_.path(), &images)) {
673 // Couldn't read image data from disk.
674 ReportFailure(COULD_NOT_READ_IMAGE_DATA_FROM_DISK,
675 l10n_util::GetStringFUTF16(
676 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
677 ASCIIToUTF16("COULD_NOT_READ_IMAGE_DATA_FROM_DISK")));
678 return false;
681 // Delete any images that may be used by the browser. We're going to write
682 // out our own versions of the parsed images, and we want to make sure the
683 // originals are gone for good.
684 std::set<base::FilePath> image_paths =
685 ExtensionsClient::Get()->GetBrowserImagePaths(extension_.get());
686 if (image_paths.size() != images.size()) {
687 // Decoded images don't match what's in the manifest.
688 ReportFailure(
689 DECODED_IMAGES_DO_NOT_MATCH_THE_MANIFEST,
690 l10n_util::GetStringFUTF16(
691 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
692 ASCIIToUTF16("DECODED_IMAGES_DO_NOT_MATCH_THE_MANIFEST")));
693 return false;
696 for (std::set<base::FilePath>::iterator it = image_paths.begin();
697 it != image_paths.end(); ++it) {
698 base::FilePath path = *it;
699 if (path.IsAbsolute() || path.ReferencesParent()) {
700 // Invalid path for browser image.
701 ReportFailure(INVALID_PATH_FOR_BROWSER_IMAGE,
702 l10n_util::GetStringFUTF16(
703 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
704 ASCIIToUTF16("INVALID_PATH_FOR_BROWSER_IMAGE")));
705 return false;
707 if (!base::DeleteFile(extension_root_.Append(path), false)) {
708 // Error removing old image file.
709 ReportFailure(ERROR_REMOVING_OLD_IMAGE_FILE,
710 l10n_util::GetStringFUTF16(
711 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
712 ASCIIToUTF16("ERROR_REMOVING_OLD_IMAGE_FILE")));
713 return false;
717 const std::string& install_icon_path =
718 IconsInfo::GetIcons(extension_.get())
719 .Get(extension_misc::EXTENSION_ICON_LARGE,
720 ExtensionIconSet::MATCH_BIGGER);
722 // Write our parsed images back to disk as well.
723 for (size_t i = 0; i < images.size(); ++i) {
724 if (BrowserThread::GetBlockingPool()->IsShutdownInProgress()) {
725 // Abort package installation if shutdown was initiated, crbug.com/235525
726 ReportFailure(
727 ABORTED_DUE_TO_SHUTDOWN,
728 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
729 ASCIIToUTF16("ABORTED_DUE_TO_SHUTDOWN")));
730 return false;
733 const SkBitmap& image = get<0>(images[i]);
734 base::FilePath path_suffix = get<1>(images[i]);
735 if (path_suffix.MaybeAsASCII() == install_icon_path)
736 *install_icon = image;
738 if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) {
739 // Invalid path for bitmap image.
740 ReportFailure(INVALID_PATH_FOR_BITMAP_IMAGE,
741 l10n_util::GetStringFUTF16(
742 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
743 ASCIIToUTF16("INVALID_PATH_FOR_BITMAP_IMAGE")));
744 return false;
746 base::FilePath path = extension_root_.Append(path_suffix);
748 std::vector<unsigned char> image_data;
749 // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even
750 // though they may originally be .jpg, etc. Figure something out.
751 // http://code.google.com/p/chromium/issues/detail?id=12459
752 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) {
753 // Error re-encoding theme image.
754 ReportFailure(ERROR_RE_ENCODING_THEME_IMAGE,
755 l10n_util::GetStringFUTF16(
756 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
757 ASCIIToUTF16("ERROR_RE_ENCODING_THEME_IMAGE")));
758 return false;
761 // Note: we're overwriting existing files that the utility process wrote,
762 // so we can be sure the directory exists.
763 const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]);
764 int size = base::checked_cast<int>(image_data.size());
765 if (base::WriteFile(path, image_data_ptr, size) != size) {
766 // Error saving theme image.
767 ReportFailure(
768 ERROR_SAVING_THEME_IMAGE,
769 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
770 ASCIIToUTF16("ERROR_SAVING_THEME_IMAGE")));
771 return false;
775 return true;
778 bool SandboxedUnpacker::RewriteCatalogFiles() {
779 base::DictionaryValue catalogs;
780 if (!ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) {
781 // Could not read catalog data from disk.
782 ReportFailure(COULD_NOT_READ_CATALOG_DATA_FROM_DISK,
783 l10n_util::GetStringFUTF16(
784 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
785 ASCIIToUTF16("COULD_NOT_READ_CATALOG_DATA_FROM_DISK")));
786 return false;
789 // Write our parsed catalogs back to disk.
790 for (base::DictionaryValue::Iterator it(catalogs); !it.IsAtEnd();
791 it.Advance()) {
792 const base::DictionaryValue* catalog = NULL;
793 if (!it.value().GetAsDictionary(&catalog)) {
794 // Invalid catalog data.
795 ReportFailure(
796 INVALID_CATALOG_DATA,
797 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
798 ASCIIToUTF16("INVALID_CATALOG_DATA")));
799 return false;
802 base::FilePath relative_path = base::FilePath::FromUTF8Unsafe(it.key());
803 relative_path = relative_path.Append(kMessagesFilename);
804 if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) {
805 // Invalid path for catalog.
806 ReportFailure(
807 INVALID_PATH_FOR_CATALOG,
808 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
809 ASCIIToUTF16("INVALID_PATH_FOR_CATALOG")));
810 return false;
812 base::FilePath path = extension_root_.Append(relative_path);
814 std::string catalog_json;
815 JSONStringValueSerializer serializer(&catalog_json);
816 serializer.set_pretty_print(true);
817 if (!serializer.Serialize(*catalog)) {
818 // Error serializing catalog.
819 ReportFailure(ERROR_SERIALIZING_CATALOG,
820 l10n_util::GetStringFUTF16(
821 IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
822 ASCIIToUTF16("ERROR_SERIALIZING_CATALOG")));
823 return false;
826 // Note: we're overwriting existing files that the utility process read,
827 // so we can be sure the directory exists.
828 int size = base::checked_cast<int>(catalog_json.size());
829 if (base::WriteFile(path, catalog_json.c_str(), size) != size) {
830 // Error saving catalog.
831 ReportFailure(
832 ERROR_SAVING_CATALOG,
833 l10n_util::GetStringFUTF16(IDS_EXTENSION_PACKAGE_INSTALL_ERROR,
834 ASCIIToUTF16("ERROR_SAVING_CATALOG")));
835 return false;
839 return true;
842 void SandboxedUnpacker::Cleanup() {
843 DCHECK(unpacker_io_task_runner_->RunsTasksOnCurrentThread());
844 if (!temp_dir_.Delete()) {
845 LOG(WARNING) << "Can not delete temp directory at "
846 << temp_dir_.path().value();
850 } // namespace extensions